C# Interview Question #149

What is Parallel.ForEachAsync?

Advanced Async, Parallelism & Threading Senior Advanced

Quick Interview Answer

Parallel.ForEachAsync is an asynchronous parallel loop available in modern .NET. It allows each iteration to await asynchronous work while controlling the degree of parallelism.

Detailed Explanation

Parallel.ForEachAsync is an asynchronous parallel loop available in modern .NET. It allows each iteration to await asynchronous work while controlling the degree of parallelism.

It can be useful for processing many independent I/O operations, such as calling external services, provided the downstream system can safely handle the concurrency.

Concurrency should normally be bounded to avoid exhausting database connections, sockets, API rate limits, memory, or other resources.

Code Example

await Parallel.ForEachAsync(
    ids,
    new ParallelOptions
    {
        MaxDegreeOfParallelism = 4
    },
    async (id, cancellationToken) =>
    {
        await ProcessAsync(id, cancellationToken);
    });