DEV Community

Ali Kolahdoozan
Ali Kolahdoozan

Posted on

Parallel Class in .NET ! – Part 2

Image description

In the first part, I have talked about the Parallel class in .NET and then Parallel.For has been explained with some examples.

You can find the first part link here : https://dev.to/alikolahdoozan/parallel-class-in-net-part-1-2hc7

In this article, I am going to continue by explaining Parallel.ForEach and Parallel.ForEachAsync as the second and third items that I have mentioned in part 1.
Since I have already gone through the theory side of the concept in Part 1, let’s start some examples, but before doing that, please have a look at the below pic.

Image description

I have created a region for Parallel.For and commented everything related to then I created a new region as well for Parallel.ForEach so things won’t be such a mess in the source code.

First of all, I create a simple Array of String like below.

Image description
If I want to make any processing through this area in a parallel, I can use Parallel.Foreach like below.

Image description
As you can see, the first parameter is the array that we want to process and the second is the item that we can use from the loop at each iteration. This one also does not give you a sequential result since everything is done in parallel.

Let’s create a small Async function like below.

Image description
I want to use this method in my ForEach Loop so since my method is an Async method, better to use ForEachAsync like what I have done in the below screen shoot, but please pay attention, we need to add one more parameter that is Cancellationtoken to the loop parameters.

Image description

So if I run, you will see something like this:

Image description
The next and last part is showing you how to use Parallel.Invoke very fast with some small examples.

Lazy to write 3-5 line of simple code ?. I have provided the Github link for you :

https://github.com/AliCharper/ParallelClassExercise

Wish you all the best...
We ❤️ .NET !
Ali

Top comments (1)

Collapse
 
moslemhady profile image
Moslem

Amazing, as always. Thanks.