Task Parallel Library(TPL) to Write Multithreaded Code

Learn how to write multithreaded or parallel code using TPL.

Sukhpinder Singh | .Net Developer
The Startup

--

I am a big fan of executing multi-threads in an application, and it is interesting to see how quickly parallelism can solve a complex query.

Let’s understand TPL with the following content:

  • Write a simple “Parallel.For” loop
  • Write a simple “Parallel.ForEach” loop
  • Cancel “Parallel.For” or “Parallel.ForEach” loop
  • Exception Handling in parallel loops

The “Parallel.For” Loop

The below function takes the directory name from the command line and uses the “TPL For loop” to yield results.

Let’s consider an example of iterating a directory and output the number of files inside the directory, not subfolder files though, along with total files size in bytes.

--

--

Sukhpinder Singh | .Net Developer
The Startup

Programmer by heart | C# | .Net 6 | .Net 8 | dotnet | dotnetcore | Kubernetes | Angular | AWS | Remember to 👏 Linktree: https://linktr.ee/sukhpindersingh