Select Page

A method can accept a CancellationToken and still ignore cancellation if it fails to pass that token to the next layer. Trace the whole path: caller, handler, service, repository, and the operation that actually waits.

This tutorial deliberately drops a token at a service boundary, proves why the pending read continues, and corrects that single call. A second program combines caller cancellation with a service time budget without disconnecting the caller.

Verified 2 November 2026 with .NET SDK 10.0.402 and runtime 10.0.13 on Linux x64. Both programs target .NET 10 with its default C# 14 language version and use only the BCL. Microsoft documents the language-version defaults. No database, web server, or external package is required.

Keep cancellation connected through every boundary

Cancellation is cooperative. The source requests it; each listener decides how to respond. Passing a token into a handler does not make every method called by that handler cancellable. The token must reach a supported cancellation parameter, or code must explicitly check it. See Microsoft’s cooperative cancellation model.

Responsibilities in this example
Layer Responsibility
Caller Own the source, request cancellation, and observe completion.
Handler Reject an already canceled request and forward the token.
Service Forward the caller token, or a token linked to it.
Repository Supply the received token to the cancellable wait.

Keep these internal token parameters required. That design choice makes a missing argument visible during development. It cannot prevent an intentional substitution: CancellationToken.None is an empty token that cannot be canceled, and passing it explicitly breaks this cancellation path.

Reproduce the dropped token and verify the correction

Create a console project with dotnet new console --framework net10.0. Replace Program.cs with this complete program and run dotnet run. Run the two programs in this article separately.

The repository uses a task-backed gate to represent a read that has not finished. The gate has no background producer, so the test controls its completion directly. BrokenServiceAsync accepts the caller token but passes None; ServiceAsync forwards it. The handler and repository are otherwise shared.

using System;
using System.Threading;
using System.Threading.Tasks;

sealed class Repository
{
    public TaskCompletionSource Release { get; } =
        new(TaskCreationOptions.RunContinuationsAsynchronously);
    public CancellationToken ReceivedToken { get; private set; }
    public int Exits { get; private set; }

    public async Task<int> ReadAsync(CancellationToken token)
    {
        ReceivedToken = token;
        try
        {
            await Release.Task.WaitAsync(token);
            return 42;
        }
        finally { Exits++; }
    }
}

class Program
{
    static readonly TimeSpan Limit = TimeSpan.FromSeconds(5);

    static void Require(bool condition, string message)
    {
        if (!condition) throw new InvalidOperationException(message);
    }

    // The broken service accepts a token but drops it at the next call.
    static Task<int> BrokenServiceAsync(Repository repository, CancellationToken token) =>
        repository.ReadAsync(CancellationToken.None);

    static Task<int> ServiceAsync(Repository repository, CancellationToken token) =>
        repository.ReadAsync(token);

    static async Task<int> HandleAsync(
        Repository repository, CancellationToken token, bool broken)
    {
        token.ThrowIfCancellationRequested();
        return await (broken
            ? BrokenServiceAsync(repository, token)
            : ServiceAsync(repository, token));
    }

    static async Task ExpectCanceled(Task operation)
    {
        try { await operation.WaitAsync(Limit); }
        catch (OperationCanceledException) when (operation.IsCanceled) { return; }
        throw new InvalidOperationException("Expected a canceled operation.");
    }

    static async Task Round(bool broken)
    {
        using var caller = new CancellationTokenSource();
        var repository = new Repository();
        Task<int> operation = HandleAsync(repository, caller.Token, broken);
        try
        {
            Require(!operation.IsCompleted, "Expected a pending read.");
            Require(repository.ReceivedToken ==
                (broken ? CancellationToken.None : caller.Token), "Wrong leaf token.");
            caller.Cancel();
            if (broken)
            {
                Require(!operation.IsCompleted, "Dropped token unexpectedly canceled work.");
                Require(repository.Exits == 0, "Read unexpectedly exited.");
                repository.Release.SetResult();
                Require(await operation.WaitAsync(Limit) == 42, "Rescue did not complete.");
            }
            else
            {
                await ExpectCanceled(operation);
                Require(!repository.Release.Task.IsCompleted, "Cancellation opened the gate.");
            }
            Require(repository.Exits == 1, "Read did not leave its finally block.");
        }
        finally
        {
            repository.Release.TrySetResult();
            try { await operation.WaitAsync(Limit); }
            catch (OperationCanceledException) when (operation.IsCanceled) { }
        }
    }

    static async Task Main()
    {
        for (int i = 0; i < 50; i++) await Round(broken: true);
        Console.WriteLine("Dropped token: 50 reads ignored caller cancellation; rescued");
        for (int i = 0; i < 50; i++) await Round(broken: false);
        Console.WriteLine("Forwarded token: 50 reads canceled; finally ran once each");

        using var canceled = new CancellationTokenSource();
        canceled.Cancel();
        var untouched = new Repository();
        await ExpectCanceled(HandleAsync(untouched, canceled.Token, broken: false));
        Require(untouched.Exits == 0, "Pre-canceled request entered the repository.");
        Console.WriteLine("Pre-canceled token: handler rejected work before repository entry");

        using var caller = new CancellationTokenSource();
        var successful = new Repository();
        successful.Release.SetResult();
        Task<int> result = HandleAsync(successful, caller.Token, broken: false);
        Require(await result.WaitAsync(Limit) == 42, "Successful read failed.");
        caller.Cancel();
        Require(result.IsCompletedSuccessfully && successful.Exits == 1,
            "Late cancellation changed a completed result.");
        Console.WriteLine("Success: 42; later cancellation left the completed result intact");
    }
}
Dropped token: 50 reads ignored caller cancellation; rescued
Forwarded token: 50 reads canceled; finally ran once each
Pre-canceled token: handler rejected work before repository entry
Success: 42; later cancellation left the completed result intact

The failure assertion does not depend on sleeping for a few milliseconds. Calling the handler reaches the incomplete repository wait before returning its pending task. The test inspects the exact token received there, cancels the caller, and checks that the broken operation is still pending. Since the gate is closed and its wait has no cancellable token, caller cancellation has no route to complete it. The test opens the gate explicitly to rescue that read and awaits it.

The correction is the argument to ReadAsync: forward token. Each corrected read must become canceled, and its finally block must have run exactly once before the handler’s completion is accepted. Both paths repeat 50 times. The final checks cover a pre-canceled request and a successful read whose completed result survives a later cancellation request. These are correctness checks, not timing or throughput measurements.

The five-second WaitAsync calls bound observation and cleanup. An unhandled timeout means the lab failed; it is not a successful cancellation result. The cleanup block opens the gate and observes the original operation, including cancellation. Do not silently detach a task just because waiting for it timed out.

Distinguish canceling a wait from canceling its producer

Task.WaitAsync creates an asynchronous wait that can end when its token is canceled or its timeout expires. In the corrected fixture, canceling the wait does not complete the underlying gate: the program asserts that the gate remains closed. No real I/O is running in this simulation.

When replacing the gate with an actual database or network operation, pass the received token to that API’s documented cancellation overload and verify its contract. Wrapping an existing task in WaitAsync(token) alone supplies a cancellation signal to the wait; it does not pass a token into the operation that originally created the task. That distinction matters when the producer owns resources or can still produce side effects.

Add a service budget while preserving caller cancellation

Creating a fresh, unrelated timeout source in a service would give the leaf a different cancellation path from the caller. Instead, CreateLinkedTokenSource creates a source that becomes canceled when either supplied token is canceled. The service owns and disposes the linked source; its callers continue to own their original sources.

This second complete program uses Task.Delay(Timeout.Infinite, token) as a cancellable stand-in for a pending leaf operation. The budget source schedules cancellation with CancelAfter. The 20-millisecond setting only triggers the budget path: the assertions do not require cancellation at an exact elapsed time.

using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static readonly TimeSpan Limit = TimeSpan.FromSeconds(5);

    static async Task ReadAsync(CancellationToken token, Action onExit)
    {
        try { await Task.Delay(Timeout.Infinite, token); }
        finally { onExit(); }
    }

    static async Task ServiceAsync(
        CancellationToken caller, CancellationToken budget, Action onExit)
    {
        using var linked = CancellationTokenSource.CreateLinkedTokenSource(caller, budget);
        await ReadAsync(linked.Token, onExit);
    }

    static async Task Round(bool cancelCaller)
    {
        using var caller = new CancellationTokenSource();
        using var budget = new CancellationTokenSource();
        int exits = 0;
        Task operation = ServiceAsync(caller.Token, budget.Token, () => exits++);
        try
        {
            if (cancelCaller) caller.Cancel();
            else budget.CancelAfter(TimeSpan.FromMilliseconds(20));

            try { await operation.WaitAsync(Limit); }
            catch (OperationCanceledException) when (operation.IsCanceled) { }

            if (!operation.IsCanceled || exits != 1)
                throw new InvalidOperationException("Cancellation or cleanup failed.");
            if (cancelCaller ? budget.IsCancellationRequested : caller.IsCancellationRequested)
                throw new InvalidOperationException("Cancellation flowed into the other parent.");
        }
        finally
        {
            caller.Cancel();
            try { await operation.WaitAsync(Limit); }
            catch (OperationCanceledException) when (operation.IsCanceled) { }
        }
    }

    static async Task Main()
    {
        for (int i = 0; i < 25; i++) await Round(cancelCaller: true);
        Console.WriteLine("Linked token: caller canceled 25 reads; budget source stayed active");
        for (int i = 0; i < 25; i++) await Round(cancelCaller: false);
        Console.WriteLine("Linked token: budget canceled 25 reads; caller source stayed active");
        Console.WriteLine("Cleanup: all 50 reads exited before their linked sources were disposed");
    }
}
Linked token: caller canceled 25 reads; budget source stayed active
Linked token: budget canceled 25 reads; caller source stayed active
Cleanup: all 50 reads exited before their linked sources were disposed

The caller path runs 25 times and the budget path runs 25 times. Each requires a canceled task and exactly one leaf exit. Each also checks that the other parent source remains uncanceled before cleanup. These tests show both inputs can stop the leaf without canceling the other parent. The linked token does not by itself tell you which input fired; this lab selects one input per run rather than resolving simultaneous requests.

The service awaits the leaf inside the linked source’s using scope, so disposal happens after leaf completion, including its finally. Disposing a CancellationTokenSource releases its resources; disposal itself does not request cancellation. Keep source ownership explicit, request cancellation when needed, and observe the work before disposing resources it still needs.

Apply the same checks to your own call chain

  1. Start at the caller and inspect every method signature and call argument down to the cancellable operation. Look for None, an omitted optional token, or an unrelated source.
  2. Test cancellation after the leaf starts. A pre-canceled handler test alone cannot detect a token dropped deeper in the call chain.
  3. Test normal completion and pre-cancellation separately. Do not convert every cancellation exception into a successful value such as an empty result unless that is an explicit application contract.
  4. When adding a time budget, test both caller and budget cancellation, then assert that started work has finished its cleanup. Keep observation timeouts separate from assertions that the operation actually canceled.

These BCL fixtures verify token wiring and lifetime in one controlled process. They do not establish the cancellation or rollback behavior of a specific database provider or remote service. Add integration tests for that dependency before relying on cancellation to prevent side effects.

For stalls caused by synchronous blocking, continue with diagnosing an async deadlock. For worker availability and circular dependencies, see thread pool starvation versus deadlock. Those tutorials investigate different causes of pending work; this one verifies whether a cancellation request can reach its listener.

Share This