2.14 — CancellationToken and Cooperative Cancellation¶
← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.13 Async deadlocks · Next: 2.15 async void
Markers: 🔥 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- Cancellation in .NET is cooperative. Nothing is forcibly stopped — the token is a request, and your code has to check it.
- Pass the token down through every async call. A token you accept and ignore is worse than useless, because it looks like cancellation works.
OperationCanceledExceptionis a normal outcome, not an error. Do not log it as one.
The concept¶
A user opens a page that runs a 30-second report, waits three seconds, and closes the tab. Without cancellation, your server keeps working for the remaining 27 seconds — running the query, building the result, serialising it — and then writes it to a connection that is already gone.
Multiply that by every impatient user and you are burning a significant fraction of your capacity on work nobody will ever see.
CancellationToken fixes that, but only cooperatively. There is no way to forcibly kill
running code in .NET — an old method called Thread.Abort tried, and it was so dangerous
(it could interrupt code mid-way through updating shared state) that it is removed entirely
in modern .NET.
So cancellation works like tapping someone on the shoulder and saying "you can stop now." They have to notice, and they choose a sensible moment to stop. If they never look up, they carry on regardless.
How it works¶
The two halves¶
// The SOURCE — the side that triggers cancellation
var cts = new CancellationTokenSource();
// The TOKEN — the side that observes it. Handed to the work.
CancellationToken token = cts.Token;
// Later, from anywhere:
cts.Cancel();
Keep the split clear: whoever starts the work holds the source; whoever does the work gets the token. Never pass the source down — that would let called code cancel its own caller.
Three ways to observe it¶
// 1. Throw if cancelled — the usual choice
token.ThrowIfCancellationRequested();
// 2. Check without throwing — for a clean partial exit
if (token.IsCancellationRequested)
return partialResults;
// 3. Register a callback — for cleanup
token.Register(() => _logger.LogInformation("Cancelled, cleaning up"));
Passing it down — the part that actually matters¶
public async Task<Report> BuildAsync(Guid id, CancellationToken ct)
{
var orders = await _db.Orders
.Where(o => o.CustomerId == id)
.ToListAsync(ct); // ← pass it
var rates = await _http.GetFromJsonAsync<Rates>("/rates", ct); // ← and here
foreach (var order in orders)
{
ct.ThrowIfCancellationRequested(); // ← check in long loops
Process(order);
}
return new Report(orders, rates);
}
A token you accept and do not use is a lie. The signature promises cancellability and the implementation ignores it. This is extremely common in real code and worth checking for in a review.
Timeouts¶
CancellationTokenSource has a built-in timer:
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
await LongRunningAsync(cts.Token); // throws after 30s
Combining tokens¶
Very common in ASP.NET Core — you want "cancel if the client disconnects or if 30 seconds pass":
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
requestAborted, timeout.Token);
await DoWorkAsync(linked.Token); // cancels on whichever fires first
⚠️ CreateLinkedTokenSource returns something you must dispose. Forgetting leaves the
registration attached to the parent token, which leaks memory if the parent is long-lived.
The using above is not optional.
CancellationToken.None¶
For work that genuinely must not be interrupted:
Use this deliberately, for things like writing an audit record after a state change — where stopping halfway would leave data inconsistent. Do not use it just to silence a compiler warning.
In ASP.NET Core¶
The framework gives you a token automatically. Just add it as an action parameter:
[HttpGet("report/{id:guid}")]
public async Task<IActionResult> GetReport(Guid id, CancellationToken ct)
{
// Model binding supplies HttpContext.RequestAborted here automatically
var report = await _service.BuildAsync(id, ct);
return Ok(report);
}
That token is cancelled when the client disconnects. Adding the parameter costs one word and is the single easiest performance improvement available in most controllers.
⚠️ Do not log cancellation as an error¶
When a user navigates away, you get an OperationCanceledException. That is normal, not a
failure:
// BAD — fills your error dashboards with noise
catch (Exception ex)
{
_logger.LogError(ex, "Request failed");
}
// GOOD — treat cancellation as the routine event it is
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
_logger.LogInformation("Request cancelled by client");
// Do not return an error response — nobody is listening anyway
}
catch (Exception ex)
{
_logger.LogError(ex, "Request failed");
throw;
}
Note the when (ct.IsCancellationRequested) filter. Without it you would also swallow
cancellations caused by your own timeouts, which usually are worth reporting as an
error. The filter distinguishes "the client left" from "our upstream call timed out".
TaskCanceledException inherits from OperationCanceledException, so catching the parent
covers both.
Background services¶
BackgroundService hands you a token that fires on shutdown. Honouring it is what makes
graceful shutdown work:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await ProcessBatchAsync(stoppingToken);
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
}
If you ignore stoppingToken, the host waits for its shutdown timeout (5 seconds by default)
and then kills the process mid-work. In Kubernetes that means dropped requests on every
deployment. See 24.6.
Code¶
A realistic service that does it properly throughout:
public class ExportService(AppDbContext db, IFileStore store, ILogger<ExportService> log)
{
public async Task<string> ExportAsync(Guid customerId, CancellationToken ct)
{
// Our own limit, on top of whatever the caller passed
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(5));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token);
var token = linked.Token;
try
{
var orders = await db.Orders
.Where(o => o.CustomerId == customerId)
.AsNoTracking()
.ToListAsync(token);
var csv = new StringBuilder();
foreach (var order in orders)
{
token.ThrowIfCancellationRequested(); // check inside the loop
csv.AppendLine($"{order.Id},{order.Total}");
}
// Deliberately NOT cancellable: a half-written file is worse
// than a wasted one. Finish what we started.
return await store.SaveAsync(csv.ToString(), CancellationToken.None);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
log.LogInformation("Export cancelled by caller");
throw;
}
catch (OperationCanceledException)
{
// Our 5-minute limit fired — this IS worth reporting
log.LogWarning("Export timed out after 5 minutes");
throw new TimeoutException("Export took too long");
}
}
}
The three deliberate decisions there are all worth explaining in an interview:
- Linked token so both the caller's cancellation and our own timeout work.
ThrowIfCancellationRequestedinside the loop, because a long loop with noawaithas no other cancellation point.CancellationToken.Nonefor the file write, because a partially written file is worse than doing unnecessary work.
Interview questions¶
Q: What is a CancellationToken and how does cancellation work in .NET?
Cancellation is cooperative — nothing is forcibly stopped. A CancellationTokenSource is
held by whoever starts the work, and it hands out a CancellationToken that gets passed down
into the work. When the source is cancelled, the token's flag flips, and it is up to the code
doing the work to notice — either by calling ThrowIfCancellationRequested, by checking
IsCancellationRequested, or by passing the token to a framework method that checks it. If
nobody checks, nothing stops. There is no forcible abort in modern .NET, because the old
Thread.Abort could interrupt code halfway through mutating shared state and was removed.
Q: Where does the token come from in an ASP.NET Core controller?
You add a CancellationToken parameter to the action and model binding supplies
HttpContext.RequestAborted automatically. It fires when the client disconnects, so passing
it into your database calls and HTTP calls means the server stops working on responses nobody
will receive. It costs one parameter and is probably the cheapest throughput improvement
available in a typical controller.
Q: How should you handle OperationCanceledException?
Treat it as a normal outcome rather than an error. If a user navigates away mid-request you
will get one, and logging it at error level fills your dashboards with noise that hides real
failures. I catch it with a filter checking whether the caller's token was the one cancelled
— if so I log at information level, and if not it means our own timeout fired, which is
genuinely worth a warning or converting into a TimeoutException. Worth knowing that
TaskCanceledException derives from it, so catching the base type covers both.
Q: What is a linked token source for?
Combining several cancellation reasons into one token — typically "cancel if the client
disconnects, or if our own timeout expires". CreateLinkedTokenSource gives you a token that
fires when any of its parents fire. The important detail is that it is disposable and you
must dispose it, because it registers callbacks on the parent tokens; if the parent is
long-lived and you forget, those registrations accumulate and leak.
Traps ⚠️¶
- Accepting a token and not using it. The signature promises cancellability that does not exist. Very common.
- Not passing the token to nested calls. Cancellation stops at the first method that drops it.
- Logging
OperationCanceledExceptionas an error. It is routine traffic. - Forgetting to dispose a linked token source. It leaks registrations on the parent.
- A long CPU loop with no
awaithas no cancellation point. You must callThrowIfCancellationRequestedexplicitly. - Ignoring
stoppingTokenin aBackgroundServicebreaks graceful shutdown and drops work on every deployment. - Cancelling work that must complete can corrupt state. Use
CancellationToken.Nonedeliberately for audit writes and similar. cts.Cancel()runs registered callbacks synchronously on the cancelling thread. A slow callback blocks whoever calledCancel.
Related¶
- 2.12 Task combinators — timeouts with
WaitAsync - 2.16 Async exceptions — where cancellation fits
- 2.11 async/await internals — where the checks happen
- 21.1 Background services —
stoppingToken - 24.6 Graceful shutdown — why it matters in containers
- 19.11 Polly — timeout policies