C# - Iterate through each item from a list in parallel and wait for them all to finish

It is quite easy to iterate through each item in a list and wait for the result. All you have to do is use Parallel.ForEach() - this is meant exactly for that scenario.

If you are looking just to iterate through a normal list without anything running in parallel, then you should just use a normal foreach loop. However this article is on running each item in parallel.

A simple example on how to use this would be the following:

Parallel.ForEach(list, item => {
    DoStuff(item); //Do what you want to do

You simply pass your list to this function. It then let's you do an action on each of the items in that list. ForEach can be used on any class which implements IEnumerable - which means all sorts of collections.

Below you can see an example of this. The code creates 3 actions each writing something to the Console. Then they each wait for a different amount of time and write something again. This is to show that they run in parallel - as the last one waits for less than the first one - and thereby gets done first.

Parallel.ForEach is called and each items invoked, after they have all run something is written again. This is to show that the parallel waits for all 3 to finish. Here is the example:

Action action5Seconds = () =>
    Console.WriteLine("Start waiting for 5 seconds");
    Console.WriteLine("Waited 5 seconds");

Action action10Seconds = () =>
    Console.WriteLine("Start waiting for 10 seconds");
    Console.WriteLine("Waited 10 seconds");

Action action2Seconds = () =>
    Console.WriteLine("Start waiting for 2 seconds");
    Console.WriteLine("Waited 2 seconds");

var list = new List<Action>

Parallel.ForEach(list, action => {
    action(); //Do what you want to do

Console.WriteLine("Done waiting for all");

The results can be seen in the following image. It is easy to see that this works just as we expected it to:


I hope you enjoyed my short explaination on how to iterate a list of items in parallel and wait for them all. Do you have any comments? write them below.