With .Net 6 we got the new Parallel.ForEachAsync method from the parallel library. Previously we had to make do with Parallel.ForEach method which had no support for async, which is why we now have Parallel.ForEachAsync
. Using this you can now use the await
key word inside of the action that you execute on each element in the list. Just like in ForEach
it executes the actions in parallel but waits for all of them to finish.
Below is a small example on how to use Parallel.ForEachAsync
:
var list = new List<(string name, int waitTime)>{
("Item1",200),
("Item2",500),
("Item3",1000),
("Item4",1500),
("Item5",5000),
("Item6",20),
("Item7",50),
("Item8",100),
("Item9",150),
("Item10",500),
};
await Parallel.ForEachAsync(list, async (item, cancellationToken) =>
{
Console.WriteLine($"Called for {item.name}, will wait {item.waitTime} ms");
await Task.Delay(item.waitTime);
Console.WriteLine($"Done handling {item.name}");
});
The result from this console application looks like the following:
As you can see the items are executed in different orders depending on how long they wait. Item6
is the first to be done and Item5
the last.
I hope this short example of how to use Parallel.ForEachAsync
will help you!
That is all
By using ForEachAsync
, you can significantly improve the responsiveness and scalability of your application. The method enables asynchronous iteration over collections, allowing for parallel processing and efficient handling of time-consuming operations.
Let me know what you think in the comments down below!