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()
- which is meant exactly for this 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, 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 on how to do this, it 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");
Thread.Sleep(5000);
Console.WriteLine("Waited 5 seconds");
};
Action Action10Seconds = () =>
{
Console.WriteLine("Start waiting for 10 seconds");
Thread.Sleep(10000);
Console.WriteLine("Waited 10 seconds");
};
Action Action2Seconds = () =>
{
Console.WriteLine("Start waiting for 2 seconds");
Thread.Sleep(2000);
Console.WriteLine("Waited 2 seconds");
};
var list = new List<Action>
{
Action5Seconds,
Action10Seconds,
Action2Seconds
};
Parallel.ForEach(list, action => {
action(); //Do what you want to do
});
Console.WriteLine("Done waiting for all");
Console.ReadLine();
The results can be seen in the following image, you can see that this works just as we expected it to:
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!