C# IAsyncEnumerable Cancellation: Pass the Token Through the Whole Stream

An await foreach loop can look cancellable because its caller has a CancellationToken, yet the producer may keep waiting on network or database work after the caller has moved on. Cancellation has to travel through the async iterator into the operation that is waiting.

Editorial illustration: cancellation token flows from an async stream consumer through an iterator to a waiting I/O operation

Editorial illustration: cancellation is cooperative; it does not forcibly interrupt a thread.

Summary

  • IAsyncEnumerable<T> is a .NET async-stream abstraction consumed with C# await foreach; cancellation is cooperative.
  • Mark the iterator token with [EnumeratorCancellation] when callers pass cancellation through WithCancellation.
  • Forward the token into each cancellable operation and expect OperationCanceledException when cancellation is observed.

A complete example

This console example targets .NET 8 or later. Async iterators and IAsyncEnumerable<T> are available in modern .NET; the language compiler follows the target framework unless explicitly overridden.

using System.Runtime.CompilerServices;

static async IAsyncEnumerable<int> ReadItemsAsync(
    int count,
    [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
    for (var item = 1; item <= count; item++)
    {
        await Task.Delay(TimeSpan.FromMilliseconds(250), cancellationToken);
        yield return item;
    }
}

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
try
{
    await foreach (var item in ReadItemsAsync(20).WithCancellation(cts.Token))
        Console.WriteLine(item);
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
    Console.WriteLine("The caller stopped the stream.");
}

EnumeratorCancellationAttribute comes from System.Runtime.CompilerServices. It tells the compiler how the token supplied to the enumerator is combined with the iterator method’s token parameter. WithCancellation supplies a token to enumeration; it does not add that token to arbitrary work inside the iterator. Microsoft explains the pattern in C# async streams and the attribute API reference.

Cancellation is a request, not a forced stop

A token is a cooperative signal. Task.Delay, HttpClient methods and many .NET APIs accept it and stop waiting when cancellation is requested. A third-party API may ignore it, or CPU work may never check it. The caller cannot safely force such an operation to stop.

For CPU work between yields, check periodically with cancellationToken.ThrowIfCancellationRequested(). For a network request, pass the token into the call, for example await client.GetAsync(uri, cancellationToken). See our guide to passing cancellation through async methods for the same end-to-end rule. Passing it only to WithCancellation cannot cancel an HTTP request the iterator started without a token.

Cancellation usually surfaces as OperationCanceledException (some APIs use TaskCanceledException). Decide where to handle it. A disconnected web request may be routine; an operator-canceled import may need a log entry and cleanup. Catching and swallowing every cancellation can make callers believe the stream finished normally.

Know which token owns the stream

There are two common styles: pass the token directly to ReadItemsAsync(token), or call ReadItemsAsync().WithCancellation(token). [EnumeratorCancellation] makes the second style work for an iterator’s designated token parameter. If callers can supply both tokens, define how their lifetimes combine and which component owns cancellation.

await foreach disposes the async enumerator when the loop exits, including when an exception breaks it. That cleanup is useful, but it does not undo side effects already performed. If the stream writes records, make each operation safe to stop between items and decide whether partial work is retained or rolled back.

Test the producer, not just the loop

A useful test checks that the awaited operation observes cancellation and that the consumer exits promptly. Also test normal completion: overly broad cancellation handling can turn genuine failures into apparent success. When shutdown remains slow, identify the operation currently awaited. If your worker also buffers jobs, bounded channels and backpressure help limit queued work, though they do not replace cancellation. If it has no token overload, consider a safe timeout boundary or a different API. Task.Run does not make synchronous blocking work cancellable; it only moves it to another thread.

Common mistakes

  • Using WithCancellation and assuming all I/O is canceled: forward the token to each relevant API.
  • Forgetting [EnumeratorCancellation]: the enumerator’s token may not reach the iterator parameter as intended.
  • Treating cancellation as successful completion: preserve the distinction where callers need it.
  • Catching cancellation too broadly: let caller cancellation reach the correct boundary.
  • Assuming cancellation rolls back yielded items: previously processed records remain processed without explicit compensation.

My Take

When an async stream hangs during shutdown, inspect the producer first. The consumer can request cancellation cleanly, but only the awaited operation can respond. Passing the token end to end makes request aborts and worker shutdown easier to reason about.

Bottom Line

Accept a token in the iterator, mark it with [EnumeratorCancellation], pass it into cancellable I/O and handle expected cancellation at the right boundary. Test prompt cancellation and ordinary completion in the project that will run the stream.

Sources