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.

C#
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.

C#
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.

C#
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.

C#
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.

C#
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.

C#
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.

C#
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.

C#
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.

Understanding AggregateException

When multiple parallel iterations fail, the exception returned by Parallel.ForEachAsync may contain more than one failure.

The caller can inspect the AggregateException to identify the individual exceptions.

C#
try
{
    await Parallel.ForEachAsync(
        customerIds,
        new ParallelOptions
        {
            MaxDegreeOfParallelism = 5
        },
        async (customerId, cancellationToken) =>
        {
            await ProcessCustomerAsync(
                customerId,
                cancellationToken);
        });
}
catch (AggregateException aggregateException)
{
    foreach (var exception in
        aggregateException.Flatten().InnerExceptions)
    {
        logger.LogError(
            exception,
            "Parallel processing operation failed.");
    }
}

It is important to understand that not every failure from Parallel.ForEachAsync should be handled by catching AggregateException alone.

A single exception may be propagated directly, while multiple failures can be represented by AggregateException. Cancellation may also result in OperationCanceledException.

A robust error-handling strategy should account for the exception types that the application can actually receive.

A Production-Oriented Implementation

The following example brings together concurrency control, linked cancellation, logging, and exception handling.

The service processes customer records and stops the remaining work when an unexpected operation fails.

C#
public sealed class CustomerProcessingService
{
    private readonly ILogger<CustomerProcessingService> _logger;

    public CustomerProcessingService(
        ILogger<CustomerProcessingService> logger)
    {
        _logger = logger;
    }

    public async Task ProcessAsync(
        IEnumerable<int> customerIds,
        CancellationToken cancellationToken)
    {
        using var linkedSource =
            CancellationTokenSource.CreateLinkedTokenSource(
                cancellationToken);

        var options = new ParallelOptions
        {
            MaxDegreeOfParallelism = 5,
            CancellationToken = linkedSource.Token
        };

        try
        {
            await Parallel.ForEachAsync(
                customerIds,
                options,
                async (customerId, token) =>
                {
                    try
                    {
                        await ProcessCustomerAsync(
                            customerId,
                            token);

                        _logger.LogInformation(
                            "Customer {CustomerId} processed successfully.",
                            customerId);
                    }
                    catch (OperationCanceledException)
                        when (token.IsCancellationRequested)
                    {
                        throw;
                    }
                    catch (Exception exception)
                    {
                        _logger.LogError(
                            exception,
                            "Customer processing failed for {CustomerId}.",
                            customerId);

                        await linkedSource.CancelAsync();

                        throw;
                    }
                });
        }
        catch (OperationCanceledException)
            when (cancellationToken.IsCancellationRequested)
        {
            _logger.LogInformation(
                "Customer processing was canceled by the caller.");

            throw;
        }
        catch (OperationCanceledException)
        {
            _logger.LogWarning(
                "Parallel customer processing was canceled after an internal failure.");

            throw;
        }
        catch (Exception exception)
        {
            _logger.LogError(
                exception,
                "Customer processing operation failed.");

            throw;
        }
    }

    private async Task ProcessCustomerAsync(
        int customerId,
        CancellationToken cancellationToken)
    {
        // Perform database or API operations here.

        await Task.Delay(
            300,
            cancellationToken);
    }
}

There are several important details in this implementation.

First, the linked cancellation source combines external cancellation with cancellation requested after an internal failure.

Second, each iteration passes its cancellation token to the actual processing method.

Third, unexpected exceptions are logged with the customer ID before being rethrown.

Finally, the outer method distinguishes caller cancellation from cancellation caused by an internal processing failure.

The implementation does not pretend that cancellation rolls back completed work. If some customer records were already updated before another operation failed, those changes remain unless the application uses a transaction or a separate recovery mechanism.

Handling Partial Results When Some Operations Have Completed

Not every application should stop all processing when one operation fails.

Consider a reporting service that generates reports for 500 customers. If one customer has incomplete information, the application may still need to generate reports for the other 499 customers.

In that situation, stopping the entire loop may not be appropriate.

Instead, the application can record failures and continue processing.

C#
var failedCustomers = new ConcurrentBag<int>();

await Parallel.ForEachAsync(
    customerIds,
    new ParallelOptions
    {
        MaxDegreeOfParallelism = 5
    },
    async (customerId, cancellationToken) =>
    {
        try
        {
            await ProcessCustomerAsync(
                customerId,
                cancellationToken);
        }
        catch (OperationCanceledException)
            when (cancellationToken.IsCancellationRequested)
        {
            throw;
        }
        catch (Exception exception)
        {
            failedCustomers.Add(customerId);

            logger.LogError(
                exception,
                "Failed to process customer {CustomerId}",
                customerId);
        }
    });

ConcurrentBag is used because multiple iterations may add failed customer IDs at the same time.

After processing completes, the application can inspect failedCustomers and decide whether to retry those records or report partial completion.

This approach is useful for independent operations where one failure should not prevent other items from being processed.

The important decision is whether the business workflow requires fail-fast behavior or best-effort processing.

Common Mistakes to Avoid

Assuming Cancellation Stops Every Operation Immediately

Cancellation is cooperative. An operation must observe and respond to its cancellation token.

If an operation is blocked inside code that does not support cancellation, it may continue running after cancellation is requested.

Always pass cancellation tokens to supported asynchronous APIs.

Catching Exceptions Without Rethrowing Them

Logging an exception and then continuing can hide failures from the caller.

If the application requires fail-fast behavior, request cancellation and rethrow the exception.

Treating Every OperationCanceledException as a Failure

Cancellation may be expected during application shutdown, request cancellation, or another iteration's failure.

Handle cancellation separately from unexpected exceptions.

Using Too Much Parallelism

Increasing MaxDegreeOfParallelism does not always improve performance.

Too many concurrent operations can exhaust database connections, overload external APIs, increase memory usage, or create unnecessary contention.

Choose concurrency limits based on the capacity of the dependencies being used.

Assuming Completed Operations Can Be Reversed

Stopping the remaining iterations does not undo completed database updates, sent emails, or external API calls.

If the workflow requires consistency across multiple operations, use transactions where possible or design compensating actions.

Forgetting to Dispose CancellationTokenSource

CancellationTokenSource owns resources and should be disposed when it is no longer needed.

Using a using statement ensures that the linked cancellation source is cleaned up when the method exits.

Testing Failure and Cancellation Scenarios

Parallel processing should be tested under more than normal conditions.

A useful test suite should include:

  1. All operations complete successfully.

  2. One operation fails while other operations are running.

  3. Multiple operations fail close together.

  4. The caller cancels the operation.

  5. An operation observes cancellation during an asynchronous call.

  6. An operation does not support cancellation and takes longer to finish.

  7. Some operations complete before another operation fails.

  8. The application verifies that no new work is started after failure cancellation is observed.

For deterministic tests, use controlled tasks, TaskCompletionSource, and explicit synchronization rather than relying on arbitrary delays.

This helps avoid flaky tests caused by unpredictable thread scheduling.

Best Practices for Parallel.ForEachAsync

When using Parallel.ForEachAsync in production applications, follow these practices:

  • Configure MaxDegreeOfParallelism according to available resources.

  • Pass cancellation tokens to all supported asynchronous operations.

  • Use linked cancellation when an internal failure must stop remaining work.

  • Log exceptions with enough context to identify the failed item.

  • Rethrow unexpected exceptions when the caller needs to know that processing failed.

  • Separate cancellation from actual processing failures.

  • Decide whether the workflow requires fail-fast behavior or partial results.

  • Use transactions or compensation when completed operations must be reversed.

  • Avoid blocking calls inside asynchronous loop bodies.

  • Test failure, cancellation, and partial-completion scenarios.

These practices make parallel execution easier to control and troubleshoot.

Summary

Parallel.ForEachAsync is a useful .NET feature for processing multiple asynchronous operations concurrently. However, parallel execution requires a clear strategy for handling failures and cancellation.

When an iteration throws an exception, the parallel loop stops scheduling additional work and coordinates cancellation of remaining operations. Operations that are already running may still need time to observe cancellation and finish their cleanup.

For workflows that require fail-fast behavior, a linked CancellationTokenSource can request cancellation when an unexpected failure occurs. Each operation should receive the cancellation token and pass it to the APIs it calls.

Not every workload should stop when one item fails. Independent operations may be better handled through partial-result processing, where failures are recorded and the remaining items continue.

The most important decision is to align exception handling with business requirements. By controlling concurrency, propagating cancellation, preserving error details, and testing failure scenarios, developers can build safer and more predictable parallel processing systems in .NET.