الانتقال إلى المحتوى
.NETC#· 7 دقائق للقراءة

A CancellationToken Cancels Nothing by Itself: Cooperative Cancellation in .NET

Cancel() only raises a flag. Work stops when the code doing it checks the token or hands it to an API that does.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A user starts the yearly sales export, waits ten seconds and closes the tab. The endpoint takes a CancellationToken, so the team assumes the work stops when the client leaves. The logs say otherwise: the server keeps sending all twelve monthly queries to the sales service and builds a CSV that nobody will ever download. On a busy day, abandoned exports pile up and slow down everyone else. The token was accepted, and then ignored.

The common misconception

The belief is that a CancellationToken works like a remote kill switch. Pass one into a method, call Cancel() somewhere else, and the method stops right there, whatever it was doing.

It's easy to see why. The names suggest it: Cancel(), CancellationToken, and ASP.NET Core hands every endpoint a token tied to the request. Built-in methods like HttpClient.GetStringAsync and EF Core's ToListAsync really do stop quickly when the token you pass them is canceled, so cancellation seems automatic. And if you come from older .NET Framework code, Thread.Abort really could stop a thread from the outside.

But a token is only a signal. Something on the other side has to look at it.

What actually happens

The source signals, the token listens

A CancellationTokenSource creates the token and is the only object that can cancel it. The token itself is a small struct you pass to whoever should listen; every copy observes the same source. When you call Cancel(), three things happen: IsCancellationRequested becomes true and can never go back to false, the token's wait handle is signaled, and callbacks registered with Register run synchronously before Cancel() returns. That's the whole list. No running code is interrupted, no thread is stopped.

Why .NET doesn't just stop the work

Stopping code at an arbitrary instruction is dangerous: a lock may stay held, a file may be left half-written, a static constructor may never run. That's why Thread.Abort throws PlatformNotSupportedException on .NET Core and .NET 5+, and why Microsoft recommends a CancellationToken instead. In , the requester only asks. The code doing the work decides where it's safe to stop: after the current row, after rolling back a transaction, or not at all once a step is past the point of no return.

Three ways code listens

  • Forward the token to every API that accepts one: HttpClient, EF Core queries, stream reads and writes, Task.Delay, SemaphoreSlim.WaitAsync. They watch the token for you and usually throw OperationCanceledException when it fires.
  • Poll it in CPU-bound loops: check IsCancellationRequested, or call ThrowIfCancellationRequested(), between items.
  • Register a callback for a blocking operation that can't take a token, so the callback can unblock it, for example by closing a connection. Keep it short: Cancel() waits for every callback to finish.

Code that does none of these keeps running until it's done, however many times Cancel() is called.

One missing hop breaks the chain

The token travels down the call stack only where you pass it. An endpoint can receive it, forward it to a service, and the service can still call GetFromJsonAsync(url) without it. From that call on, nothing is listening. That's exactly what happened in the export:

C# Program.cs
using System.Text;var app = WebApplication.Create(args);var http = new HttpClient { BaseAddress = new("https://sales.example.com/") };// Minimal APIs bind ct to the request's token, canceled if the client leavesapp.MapGet("/export", (CancellationToken ct) => BuildCsvAsync(http, ct));app.Run();static async Task<string> BuildCsvAsync(HttpClient http, CancellationToken ct){    var csv = new StringBuilder("month,total\n");    for (var month = 1; month <= 12; month++)    {        // ct is accepted but never used: nothing in this loop can stop        var sales = await http.GetFromJsonAsync<decimal[]>($"sales/{month}");        csv.AppendLine($"{month},{sales!.Sum()}");    }    return csv.ToString();}

In the fixed version, a client that disconnects during month 3 cancels the in-flight HTTP request, the method throws OperationCanceledException, and months 4 to 12 are never requested. Two small changes, and the token finally reaches code that listens.

What "canceled" looks like to the caller

There are two ways for cooperative code to stop. It can simply return, but then its task ends as RanToCompletion and the caller can't tell it was cut short. Or it can throw OperationCanceledException, which is what ThrowIfCancellationRequested() does. An async method that throws it ends in the Canceled state, and awaiting that task throws the exception again, so the caller knows exactly what happened. Either way, some work may still finish after Cancel() is called: cancellation takes effect at the next check, not at the next instruction.

Myth vs reality

MythReality
Passing a token to a method makes it stoppableOnly code that checks the token, or forwards it to an API that does, can stop
Cancel() stops the running codeIt sets a flag and runs registered callbacks; the running code decides when to stop
Task.Run(work, token) cancels workThe token only keeps work from starting; the delegate never receives it
Cancellation takes effect immediatelyWork stops at the next check or cancelable call, sometimes after finishing an item
A canceled operation is a failureIt ends with OperationCanceledException, an outcome to handle apart from real errors

How to apply it in your project

  1. Accept a token in every slow async methodAny method that does I/O or long-running work should take a CancellationToken, conventionally as the last parameter. In ASP.NET Core, endpoints and controller actions can simply declare one.
  2. Forward it on every callPass the token to every method that accepts it. Analyzer rule CA2016 finds the calls you missed; it's enabled as a suggestion in .NET 10, which is easy to overlook.
  3. Check it in long loopsIn CPU-bound loops or batch jobs, call ct.ThrowIfCancellationRequested() once per item or batch, so a canceled job stops within one unit of work.
  4. Treat cancellation as its own outcomeCatch OperationCanceledException separately from real errors, and don't log it as a failure. For timeouts, create the source with a delay and dispose it when done:
C# Program.cs
using var http = new HttpClient();using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));try{    string page = await http.GetStringAsync("https://example.com/", cts.Token);    Console.WriteLine($"Downloaded {page.Length} characters");}catch (OperationCanceledException) when (cts.IsCancellationRequested){    Console.WriteLine("Gave up after 5 seconds"); // a timeout, not a bug}

Key takeaways

  • Cancel() sets a flag, signals a wait handle and runs callbacks; it never interrupts running code.
  • Work stops only where code checks the token or passes it to an API that watches it.
  • One call that drops the token ends cancellation for everything below it; CA2016 helps you find those calls.
  • Throw OperationCanceledException with ThrowIfCancellationRequested() so callers see a canceled task, and handle it apart from real failures.

📚 المصادر

  1. Cancellation in Managed Threads — Microsoft Learn
  2. Task Cancellation — Microsoft Learn
  3. CA2016: Forward the CancellationToken parameter to methods that take one — Microsoft Learn
  4. Task.Run Method (System.Threading.Tasks) — Microsoft Learn
  5. Breaking change: Thread.Abort is obsolete — Microsoft Learn

التعليقات (0)