C# - Iterate through all items in a list In parallel and wait for them all to finish

You can easily iterate through each item in a list, run a function on each and wait for all to finish. All you have to do is use Parallel.ForEach() - which is meant exactly for this scenario.

If you are using async / await take a look at my post on ForEachAsync. The principles are the same, but it fits well with async / await.

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 to do a sequential loop, but this article is on running each item in parallel.

Iterating through a list in parallel and running an action on each item

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 pass your list to the ForEach method as the first parameter and the second parameter is the action you want to execute on every item. ForEach can be used on any class which implements IEnumerable - which means all sorts of collections.

Below you can see an example where we demonstrate that it executes in parallel and waits for all functions on items to finish. The below creates three actions each writing something to the Console. Then the three actions 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 item invoked, after they have all run something is written again. This is to show that the parallel waits for all three 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, you can see that this works just as expected:


The one that waits for ten seconds is last even though it was second in the list, "Done waiting for all" is written when all three items in the list are done. It is easier to see if you try and execute the code on your own.

That is all!

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