advanced · 29 minute study
Cancellation is a request; stale results still need a guard
Stop wasting work after a user leaves a screen and prevent an older search response from replacing a newer one.
Useful preparation · 1 prerequisite
Use this as a map, not a lock. If these ideas are familiar, continue.
- A Task represents completion, not a promise of another thread — Keep a UI responsive and a server from blocking unnecessarily while making asynchronous failures visible to the caller.
First, build a mental model
A CancellationToken communicates that work is no longer wanted. Cooperating operations decide how to observe it. A result-order guard separately decides whether a completed result still belongs to the current request.
- Pass the token through methods into cancelable I/O and waits instead of accepting it and ignoring it.
- Canceled task-based operations commonly surface OperationCanceledException when awaited; handle expected cancellation separately from a genuine failure.
- Cancellation does not undo a committed database write or guarantee that a remote server never received a request.
- A monotonically increasing request identity can reject stale results even when a dependency ignores or races with cancellation.
static async Task<int> LoadAsync(CancellationToken token)
{
await Task.Delay(1000, token);
return 42;
}
using var source = new CancellationTokenSource();
source.Cancel();
try
{
int value = await LoadAsync(source.Token);
Console.WriteLine(value);
}
catch (OperationCanceledException) when (source.IsCancellationRequested)
{
Console.WriteLine("cancelled");
}- Request cancellation
The token is already canceled before LoadAsync is called.
- Observe
Task.Delay observes that token; await propagates cancellation.
- Handle
The filtered cancellation handler runs instead of printing a fabricated result.
Production thinking
Take this beyond the example.
Give requests deadlines, forward cancellation and guard result ownership. In write workflows, cancellation and retries must respect transaction boundaries and operation identity.
Sources and further reading
Your evidence
unseen is a local learning signal, not a credential or proof of production competence.
Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.
Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.
Next lesson · Decode data and release resources at explicit boundaries →