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)>{
    ("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 is the following:

csharp-ForEachAsync

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!