Parallel processing is a useful way to improve application performance when multiple independent operations need to run at the same time. In .NET, Parallel.ForEachAsync provides a convenient way to process collections asynchronously while controlling the maximum number of concurrent operations.
It is commonly used for tasks such as calling multiple APIs, processing files, updating database records, and handling batches of background jobs.
However, parallel processing introduces an important challenge: what should happen when one operation fails?
Imagine an application processing 1,000 customer records. It starts several operations concurrently, and one operation encounters an unexpected database error. Should the application continue processing the remaining records? Should it stop immediately? What happens to operations that are already running?
The answer depends on the business requirement, but the application should always have a predictable failure-handling strategy.
Simply allowing an exception to escape from a parallel operation may stop the overall loop, but it does not automatically provide a complete application-level strategy for cancellation, cleanup, error reporting, and partial results.
In this article, we will explore how Parallel.ForEachAsync handles exceptions, how to stop remaining work when an operation fails, and how to implement clean cancellation and error handling in production .NET applications.
Understanding Parallel.ForEachAsync
Parallel.ForEachAsync executes iterations of a collection asynchronously. Unlike a normal foreach loop, it allows multiple iterations to run concurrently.
Consider a collection of customer IDs. Each customer requires an asynchronous API request.
A normal foreach loop processes one customer at a time.
foreach (var customerId in customerIds)
{
await ProcessCustomerAsync(customerId);
}If there are hundreds of customers and each request takes time, sequential processing may take longer than necessary.
Parallel.ForEachAsync allows several operations to execute at the same time.
await Parallel.ForEachAsync(
customerIds,
async (customerId, cancellationToken) =>
{
await ProcessCustomerAsync(
customerId,
cancellationToken);
});By default, the method uses a concurrency limit based on the available processing environment. However, applications should configure MaxDegreeOfParallelism when they need explicit control over the number of simultaneous operations.
var options = new ParallelOptions
{
MaxDegreeOfParallelism = 5
};
await Parallel.ForEachAsync(
customerIds,
options,
async (customerId, cancellationToken) =>
{
await ProcessCustomerAsync(
customerId,
cancellationToken);
});In this example, no more than five loop operations execute concurrently.
This limit is important when operations depend on resources such as database connections, external APIs, or file handles.
What Happens When One Parallel Operation Fails?
When an iteration throws an exception, Parallel.ForEachAsync records the failure and stops scheduling additional iterations.
However, operations that are already running may still be active. The loop coordinates cancellation of its remaining work and waits for the running operations to finish before its task completes.
If multiple iterations fail, the loop can report multiple exceptions through an AggregateException.
The important point is that an exception in one iteration does not mean every other operation has already stopped at that exact moment.
Consider the following example.
await Parallel.ForEachAsync(
customerIds,
new ParallelOptions
{
MaxDegreeOfParallelism = 5
},
async (customerId, cancellationToken) =>
{
if (customerId == 10)
{
throw new InvalidOperationException(
"Customer processing failed.");
}
await ProcessCustomerAsync(
customerId,
cancellationToken);
});When customer ID 10 fails, the parallel loop begins handling the failure and cancellation of remaining work.
But there is a problem with this implementation. It does not show how the application should handle cleanup, external cancellation, or the specific failure details.
A production implementation should make those responsibilities explicit.
Using ParallelOptions for Cancellation
Parallel.ForEachAsync accepts a ParallelOptions object that can contain a CancellationToken.
This allows the caller to stop the entire operation when cancellation is requested.
var cancellationSource =
new CancellationTokenSource();
var options = new ParallelOptions
{
MaxDegreeOfParallelism = 4,
CancellationToken = cancellationSource.Token
};
await Parallel.ForEachAsync(
customerIds,
options,
async (customerId, cancellationToken) =>
{
await ProcessCustomerAsync(
customerId,
cancellationToken);
});The cancellation token is also passed to the loop body.
This is important because cancellation should be propagated to the actual operation, not just the outer parallel loop.
For example, if ProcessCustomerAsync calls an HTTP API, the token should be passed to HttpClient.SendAsync. If it performs an asynchronous database operation, the token should be passed to the database API when supported.
Cancellation is cooperative. A method that ignores the token may continue running even after cancellation has been requested.
Stopping Remaining Work When One Operation Fails
Sometimes the requirement is stricter than ordinary exception handling.
For example, suppose an application imports a group of financial records. If one record fails validation or processing, the application must stop starting additional operations.
The application can use a linked CancellationTokenSource to combine external cancellation with internal failure cancellation.
A linked token allows either the caller or the parallel operation to request cancellation.
The following example demonstrates this approach.
public static async Task ProcessCustomersAsync(
IEnumerable<int> customerIds,
CancellationToken cancellationToken)
{
using var failureSource =
CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken);
var options = new ParallelOptions
{
MaxDegreeOfParallelism = 4,
CancellationToken = failureSource.Token
};
try
{
await Parallel.ForEachAsync(
customerIds,
options,
async (customerId, token) =>
{
try
{
await ProcessCustomerAsync(
customerId,
token);
}
catch
{
await failureSource.CancelAsync();
throw;
}
});
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
throw;
}
}This example requests cancellation when an iteration fails.
The original exception is rethrown so the loop can report the failure. The linked cancellation token also tells other running iterations that they should stop.
However, this example intentionally allows the exception to propagate. The caller still needs to decide how to report the failure and whether any completed operations need compensation or recovery.
There is another important detail: a cancellation request cannot undo work that has already completed. If one operation has already updated a database record, cancellation does not automatically roll back that update.
For workflows that require all-or-nothing behavior, use a transaction where appropriate or design explicit compensation steps.
Handling Exceptions Without Losing the Original Error
A common mistake is to catch every exception and return without recording it.
try
{
await ProcessCustomerAsync(
customerId,
cancellationToken);
}
catch
{
// Ignore the error.
}This makes the loop appear successful even when individual operations have failed.
It also makes troubleshooting difficult because the application loses important information about the failure.
A better approach is to log the exception, request cancellation, and rethrow it.
try
{
await ProcessCustomerAsync(
customerId,
cancellationToken);
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception exception)
{
logger.LogError(
exception,
"Failed to process customer {CustomerId}",
customerId);
await failureSource.CancelAsync();
throw;
}This implementation distinguishes cancellation from unexpected failures.
An OperationCanceledException is not necessarily an application error. It may indicate that the caller requested cancellation or that another iteration failed and triggered cancellation.
The exception should not be logged as an unexpected processing failure when cancellation was expected.
Join the conversation! Your thoughts help the community grow.