
A CancellationToken Cancels Nothing by Itself: Cooperative Cancellation in .NET
- كاتب موثّق
- .NET 10
محتويات المقال
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
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.
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.
What actually happens
The source signals, the token listens
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
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 throwOperationCanceledExceptionwhen it fires.Poll it in CPU-bound loops: check IsCancellationRequested, or callThrowIfCancellationRequested(), 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.
Cancel() is called.
One missing hop breaks the chain
GetFromJsonAsync(url) without it. From that call on, nothing is listening. That's exactly what happened in the export:
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();}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.ThrowIfCancellationRequested(); // cheap check before each month var sales = await http.GetFromJsonAsync<decimal[]>($"sales/{month}", ct); csv.AppendLine($"{month},{sales!.Sum()}"); } return csv.ToString();}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
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
Cancel() stops the running code | |
Task.Run(work, token) cancels work | work from starting; the delegate never receives it |
OperationCanceledException, an outcome to handle apart from real errors |
How to apply it in your project
Accept a token in every slow async method Any 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.Forward it on every call Pass 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. Check it in long loops In CPU-bound loops or batch jobs, call ct.ThrowIfCancellationRequested()once per item or batch, so a canceled job stops within one unit of work.Treat cancellation as its own outcome Catch OperationCanceledExceptionseparately from real errors, and don't log it as a failure. For timeouts, create the source with a delay and dispose it when done:
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 OperationCanceledExceptionwithThrowIfCancellationRequested()so callers see a canceled task, and handle it apart from real failures.
التعليقات (0)