C# Reference ยท Async and Concurrency
Parallel.ForEachAsync
Reference for Parallel.ForEachAsync in C# (.NET 6+): run async work per item with a degree-of-parallelism limit, cancellation and async sources.
Parallel.ForEachAsync runs an asynchronous body for every item of a sequence, with at most N bodies in flight at the same time. It is the async counterpart of Parallel.ForEach: use it for I/O-bound work such as HTTP calls, database queries or file reads, where Parallel.ForEach would waste threads blocking.
It returns a Task, so you await it. The source can be an IEnumerable<T> or an IAsyncEnumerable<T>, and the body receives the item and a CancellationToken.
await Parallel.ForEachAsync(ids, async (id, ct) => { await ProcessAsync(id, ct); });
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static class Parallel { public static Task ForEachAsync<TSource>(IEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask> body); public static Task ForEachAsync<TSource>(IEnumerable<TSource> source, ParallelOptions parallelOptions, Func<TSource, CancellationToken, ValueTask> body); public static Task ForEachAsync<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask> body); public static Task ForEachAsync<TSource>(IAsyncEnumerable<TSource> source, ParallelOptions parallelOptions, Func<TSource, CancellationToken, ValueTask> body); }
| Name | Description |
|---|---|
source |
The items to process. An IEnumerable<T> is read lazily and thread-safely. |
parallelOptions |
MaxDegreeOfParallelism, CancellationToken, TaskScheduler. |
body |
Async delegate returning ValueTask; an async lambda converts automatically. |
Returns: a Task that completes when every item has been processed or the loop has stopped.
Errors: if a body throws, the loop stops starting new items, waits for running ones, and rethrows the first exception when awaited. If the token is canceled, the task ends with OperationCanceledException.
Usage notes
- The default degree of parallelism is the processor count, not "as many as possible". For I/O-bound work you often want a higher fixed limit; for rate-limited services a lower one. Set
MaxDegreeOfParallelismexplicitly. -1means unlimited, which is dangerous for a large source: thousands of simultaneous requests.- Order is not preserved. Items start roughly in order but finish in any order. Write results to an indexed slot or a concurrent collection.
- Pass the token on. Hand the
ctparameter to every inner call so cancellation and failure stop in-flight work quickly. - Do not use it for CPU-bound work.
Parallel.ForEachis the better tool; an async body that never awaits just runs synchronously on pool threads. - Exceptions are not aggregated. Unlike
Parallel.For, only the first exception is thrown; log inside the body if you need all of them. - Alternatives:
Task.WhenAllwith aSemaphoreSlimfor the same effect on older .NET versions, or a Channel with a fixed number of consumers for pipelines. - Introduced in .NET 6. It is available on every current runtime.