Control Async Concurrency with Parallel.ForEachAsync in C#
Calling an HTTP API for every row in a large input list can be slow if done one at a time and overwhelming if every request starts at once. In .NET, Parallel.ForEachAsync provides a middle ground: run asynchronous iterations concurrently, with a configurable maximum.
This walkthrough targets .NET 6 or later and uses C# with System.Threading.Tasks. It is useful for bounded I/O work such as fetching records or processing files. It is not a promise that parallel code is always faster; downstream limits, ordering and failure behavior still need a decision.
Editorial illustration: a concurrency cap lets several async operations progress without launching the entire input at once.
Summary
Parallel.ForEachAsyncis a .NET API available from .NET 6; it is not a new C# language feature.- Set
MaxDegreeOfParallelismto bound concurrent iterations and pass cancellation through the loop. - Choose the limit based on the downstream service and measured workload; do not assume more parallelism means more throughput.
A bounded HTTP example
The following console-app example uses IHttpClientFactory via a minimal host, but the loop itself can also receive an existing HttpClient. It processes a finite list and keeps at most eight iterations active:
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using var host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services => services.AddHttpClient())
.Build();
var factory = host.Services.GetRequiredService<IHttpClientFactory>();
using var client = factory.CreateClient();
var ids = Enumerable.Range(1, 200).ToArray();
using var cancellation = new CancellationTokenSource();
await Parallel.ForEachAsync(
ids,
new ParallelOptions
{
MaxDegreeOfParallelism = 8,
CancellationToken = cancellation.Token
},
async (id, token) =>
{
var item = await client.GetFromJsonAsync<Item>(
$"https://api.example.test/items/{id}", token);
if (item is not null)
{
Console.WriteLine($"Received {item.Id}");
}
});
public sealed record Item(int Id, string Name);
This requires a .NET 6+ project and the Microsoft.Extensions.Http package/framework reference available to the project. Replace the example host name with a real service you control. GetFromJsonAsync observes the cancellation token, so cancellation can stop waiting for an in-flight request where the underlying operation supports it.
The overload accepts an IEnumerable<T> or IAsyncEnumerable<T>, plus a delegate returning ValueTask and a cancellation token through ParallelOptions. The API awaits all loop work before the call completes. The default parallelism is bounded by processor count, but for I/O-bound work a deliberate service-friendly limit is often more appropriate than relying on that default.
Choose the limit from the dependency outward
For CPU-heavy computation, processor count is a reasonable starting point to measure. For network I/O, the limiting factor may be a partner API quota, database connection pool, file server or memory. Start with a conservative value, observe latency, errors and throughput, and increase only while the dependency remains healthy.
A cap of eight means no more than eight loop bodies are active at one time; it does not guarantee eight requests per second. Request duration and service throttling determine the rate. If the API returns rate-limit responses, lower concurrency or add a documented retry policy with backoff rather than simply increasing the limit.
Cancellation and errors need a policy
Pass the provided token to every cancellable operation inside the body. The loop’s cancellation token stops scheduling or continuing work, but code that ignores the token may continue running. For a web request, link the operation to the request-aborted token; for a background job, use the job’s shutdown token.
Exceptions from loop bodies cause the overall operation to fail. Decide whether one failed item should stop the batch or whether the job should record per-item failures and continue. If partial completion matters, catch expected item-level errors inside the body, log the item identifier, and collect a structured result. Do not silently swallow every exception; that makes a “successful” batch indistinguishable from lost work.
Ordering and shared state
Concurrent iterations do not complete in input order. If the output must preserve order, store each result with its input index and reorder after the loop, or use a sequential loop. Avoid appending to a regular List<T> from multiple bodies without synchronization; use a thread-safe collection or an indexed result array when input size is fixed.
Also avoid sharing a non-thread-safe client or mutable object across iterations unless its documentation allows concurrent use. HttpClient is designed for concurrent requests, but many database contexts and custom SDK clients have stricter rules. Check the specific dependency.
When another pattern is better
Use an ordinary foreach with await when operations must remain sequential, ordering is essential, or the service allows only one request at a time. Use a queue or channel when producers and consumers run independently or work must be buffered across a longer-lived service. A parallel loop is a good fit when you already have a collection or async stream and want one operation to await the whole bounded batch.
My Take
The important setting is not the biggest number that makes a benchmark look fast; it is the largest safe concurrency for the slowest dependency in the workflow. Start small and capture per-item outcomes. That turns concurrency into a controlled throughput choice instead of a source of intermittent throttling and hard-to-reproduce failures.
Related reading
For a producer-consumer design with explicit queue backpressure, see bounded channels in C# and .NET. For time-dependent code and deterministic tests, see using TimeProvider and FakeTimeProvider.
Conclusion
Parallel.ForEachAsync gives .NET 6+ applications a compact way to run asynchronous iterations concurrently. Set a deliberate limit, propagate cancellation, and define what happens when individual items fail or finish out of order. Measure against the real dependency before increasing the cap.