Select Page

Adding WithCancellation to an await foreach loop can still leave an async stream producing items after cancellation. The consumer supplies a token, but the iterator must receive it and use it where work waits.

This tutorial reproduces that gap with a finite stream, then verifies a corrected iterator, cancellation boundaries, and cleanup. Both complete programs were compiled and run against .NET 10 in an offline Linux container on 4 November 2026, with nullable analysis and warnings treated as errors. They use only the BCL.

Reproduce a stream that ignores cancellation

Create a .NET 10 console project, then replace Program.cs with the first program. Run each program separately in that project.

dotnet new console --framework net10.0 --name StreamCancellation
cd StreamCancellation
dotnet run

The consumer requests cancellation after item 1. The iterator accepts no token and its delay has no cancellation argument. It deliberately stops after three items, so this failure demonstration does not need an infinite producer or a rescue task. The five-second source timer is another cancellation request; an iterator that ignores the token ignores that request too.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
int received = 0;
int cleaned = 0;
await foreach (int item in Ignored(() => cleaned++)
    .WithCancellation(cancellation.Token))
{
    received++;
    if (item == 1) cancellation.Cancel();
}
if (received != 3 || cleaned != 1 || !cancellation.IsCancellationRequested)
    throw new InvalidOperationException("Reproduction changed.");
Console.WriteLine("Cancellation requested after item 1; received 3 items.");
Console.WriteLine("Cleanup ran once.");

static async IAsyncEnumerable<int> Ignored(Action cleanup)
{
    try
    {
        for (int item = 1; item <= 3; item++)
        {
            await Task.Delay(1);
            yield return item;
        }
    }
    finally { cleanup(); }
}
Cancellation requested after item 1; received 3 items.
Cleanup ran once.

The assertion confirms that a cancellation request occurred, three items arrived, and cleanup ran once. This is an expected failure of cancellation wiring, not an expected compiler error. Microsoft describes WithCancellation as the way to pass a token to an async stream; the call does not replace the iterator’s responsibility to react to it.

Connect the consumer token to the iterator’s wait

The corrected Read method has two essential changes. Its optional token parameter carries EnumeratorCancellation, which identifies the parameter that receives the enumeration token. Its delay passes that parameter to the cancellable Task.Delay overload. Merely adding the attribute would leave the original uncancellable delay unchanged.

Replace the entire program with the following verification harness. It repeats four cases 50 times and throws if any count, cancellation outcome, item order, or cleanup count differs from the expected result.

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

await RunChecks().WaitAsync(TimeSpan.FromSeconds(15));
Console.WriteLine("50 rounds: complete=3, cancel-after-first=1, pre-cancel=0, break=1.");
Console.WriteLine("Cleanup ran once in each of 200 enumerations.");

static async Task RunChecks()
{
    for (int round = 0; round < 50; round++)
    {
        foreach (string mode in new[] { "complete", "cancel", "pre-cancel", "break" })
        {
            using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            int received = 0;
            int cleaned = 0;
            bool cancelled = false;
            if (mode == "pre-cancel") cancellation.Cancel();
            try
            {
                await foreach (int item in Read(() => cleaned++)
                    .WithCancellation(cancellation.Token))
                {
                    if (item != received + 1)
                        throw new InvalidOperationException("Unexpected item order.");
                    received++;
                    if (mode == "cancel") cancellation.Cancel();
                    if (mode == "break") break;
                }
            }
            catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
            {
                cancelled = true;
            }
            int expected = mode == "complete" ? 3 : mode == "pre-cancel" ? 0 : 1;
            bool expectedCancellation = mode == "cancel" || mode == "pre-cancel";
            if (received != expected || cancelled != expectedCancellation || cleaned != 1)
                throw new InvalidOperationException($"Failed case: {mode}");
        }
    }
}

static async IAsyncEnumerable<int> Read(
    Action cleanup,
    [EnumeratorCancellation] CancellationToken token = default)
{
    try
    {
        for (int item = 1; item <= 3; item++)
        {
            await Task.Delay(1, token);
            yield return item;
        }
    }
    finally { cleanup(); }
}
50 rounds: complete=3, cancel-after-first=1, pre-cancel=0, break=1.
Cleanup ran once in each of 200 enumerations.
What each case verifies
Case Items received Cancellation exception observed Cleanup calls
Normal completion 3 No 1
Cancel after first item 1 Yes 1
Cancel before enumeration 0 Yes 1
Break after first item 1 No 1

Cancellation in this test occurs at an explicit boundary, after receiving item 1 or before starting enumeration. The next delay observes the canceled token before yielding another item. The test does not depend on the one-millisecond delay taking an exact amount of time, and it does not test cancellation racing with an item already being delivered.

Each case has a five-second cancellation fallback. The whole matrix also has a 15-second observation timeout: a timeout is a failed run, not evidence of successful cancellation. These bounds are test guards, not application latency promises.

Check cleanup separately from cancellation

Microsoft’s async-stream tutorial shows the loop’s asynchronous disposal in a finally block. Here, the iterator’s finally increments a counter that must equal one after the loop exits. The early-break case checks disposal without requesting cancellation. The pre-canceled case enters this iterator’s protected body and leaves through its cancellable delay before yielding anything.

The counter stands in for resource cleanup; no file, socket, or database is opened. When adapting this pattern, put resource ownership inside the iterator’s protected scope and test the real dependency’s cancellation and disposal contract. The fixtures establish these BCL outcomes, not remote rollback or a throughput improvement.

Trace your own stream from consumer to operation

  1. Confirm the consumer supplies its token through WithCancellation.
  2. Inspect the async iterator’s token parameter and its EnumeratorCancellation attribute.
  3. Follow that parameter into the cancellable operation. Check work between waits separately if it needs cancellation checks.
  4. Test normal completion, cancellation, pre-cancellation, and early exit, then assert that owned resources have been released.

For a token lost between ordinary service methods, continue with CancellationToken propagation across application layers. For the surrounding exception-handling syntax, see Introduction to Exception Handling.

Share This