C# - How to use ForEachAsync()

With .Net 6 we get 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.

Below I have written a small example using Parallel.ForEachAsync:

var list = new List<(string name, int waitTime)>{

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 is 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 example of how to use Parallel.ForEachAsync will help you!