Module 1 · Control Flow, Cancellation, and Time Budgets · Lesson 1 of 12
CancellationToken Ownership and Propagation
The request stops waiting after step 1 was written. Did that write disappear? Follow the side-effect list in the complete program, then identify the source that requested cancellation. A cancellation signal, a task’s terminal state and a committed effect are separate observations.
Prerequisites are C# async/await, exceptions, collections and using/finally. Use a separate .NET 10 / C# 14 console project with implicit usings for each complete program. The request-handler fragments in the explanation use application-specific services; do not concatenate them into the runnable program. Minimum API versions and extra packages are noted where relevant.
Run the cancellation and side-effect trace
The application-specific snippets elsewhere in this lesson are parts of a request handler. The program below is a complete top-level console example for .NET 6+ with implicit usings enabled. It illustrates the rules in one file:
- the service owns its time budget and disposes it;
- a linked token joins that budget to the caller's token;
- exception filters classify the observed sources, prioritizing caller cancellation if both are canceled when the first filter is checked;
- a CPU loop stops only at its checkpoints.
// Who cancelled? Telling caller cancellation from a service-owned budget, and what cancellation does not undo.
var committed = new List<string>();
async Task<string> HandleAsync(string id, TimeSpan budget, TimeSpan work, CancellationToken requestAborted)
{
using var timeout = new CancellationTokenSource(budget); // owned here, disposed here
using var linked = CancellationTokenSource.CreateLinkedTokenSource(requestAborted, timeout.Token);
try
{
linked.Token.ThrowIfCancellationRequested(); // reject already-canceled work before the first side effect
committed.Add($"{id}: step 1 written"); // side effect before the wait
await Task.Delay(work, linked.Token);
committed.Add($"{id}: step 2 written");
return $"{id}: completed";
}
catch (OperationCanceledException) when (requestAborted.IsCancellationRequested)
{
return $"{id}: caller cancelled (rethrow at a real boundary; log as info)";
}
catch (OperationCanceledException) when (timeout.IsCancellationRequested)
{
return $"{id}: service budget of {budget.TotalMilliseconds} ms expired (log as a timeout; caller did not cancel)";
}
}
Console.WriteLine(await HandleAsync("A", TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(20), CancellationToken.None));
using (var caller = new CancellationTokenSource(TimeSpan.FromMilliseconds(30)))
Console.WriteLine(await HandleAsync("B", TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), caller.Token));
Console.WriteLine(await HandleAsync("C", TimeSpan.FromMilliseconds(30), TimeSpan.FromSeconds(5), CancellationToken.None));
Console.WriteLine("Side effects that survived cancellation: " + string.Join("; ", committed));
// CPU-bound work only stops at explicit checkpoints.
using var cpu = new CancellationTokenSource();
int processed = 0;
try
{
for (int i = 0; i < 1_000_000; i++)
{
if (i % 10_000 == 0) cpu.Token.ThrowIfCancellationRequested(); // checkpoint every 10,000 items
if (i == 123_456) cpu.Cancel(); // cancellation requested mid-loop
processed++;
}
}
catch (OperationCanceledException) { }
Console.WriteLine($"CPU loop stopped at the next checkpoint: processed {processed:N0} items");
// The token is a struct view of the source's state; only the source can cancel.
using var src = new CancellationTokenSource();
CancellationToken copy = src.Token;
src.Cancel();
Console.WriteLine($"Copied token sees the cancel: {copy.IsCancellationRequested}; CancellationToken.None can be cancelled: {CancellationToken.None.CanBeCanceled}");Illustrative output, not an execution transcript
The console demonstration returns diagnostic strings from its cancellation handlers so the next case can run. That means its returned tasks complete successfully; real APIs should normally propagate cancellation rather than silently convert it to success. A cancellation check before a write cannot eliminate a race with cancellation during the write.
A: completed B: caller cancelled (rethrow at a real boundary; log as info) C: service budget of 30 ms expired (log as a timeout; caller did not cancel) Side effects that survived cancellation: A: step 1 written; A: step 2 written; B: step 1 written; C: step 1 written CPU loop stopped at the next checkpoint: processed 130,000 items Copied token sees the cancel: True; CancellationToken.None can be cancelled: False
These timer-driven A/B/C outcomes are illustrative, not guaranteed scheduling or timing assertions. Under load, timer callbacks and continuations can be delayed or race. Use controlled signals or fake time for deterministic tests.
How to interpret the illustrated outcome
- A finished inside its budget, so both steps were written.
- B illustrates caller cancellation requested by a timer configured for 30 ms, not a guarantee that execution stops at exactly 30 ms. The
when (requestAborted.IsCancellationRequested)filter classified it as caller cancellation. - C illustrates cancellation requested by the service's own 30 ms timer while the caller token remains uncanceled. The second filter classified it as a timeout. Logging both as "cancelled" would hide a slow dependency.
- The side-effect list shows that B and C both kept "step 1 written". Cancellation stopped the next step but did not undo the first, which is why the side-effect discussion calls for idempotency or compensation.
- The CPU loop was asked to stop at item 123,456 but only noticed at the next checkpoint (item 130,000). Checkpoint spacing is your response-time budget.
- A copied
CancellationTokensees the source's cancel because it is a view of the source's shared state.CancellationToken.Nonecan never be cancelled, so passing it silently opts out.
Decide who owns cancellation
At an ASP.NET Core boundary, the request owns HttpContext.RequestAborted. Application services should accept that token and pass it to every operation that can safely stop:
public async Task<OrderSummary> HandleAsync(
Guid orderId,
CancellationToken cancellationToken)
{
var order = await repository.GetAsync(orderId, cancellationToken);
var price = await pricing.GetAsync(order.Sku, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
return new OrderSummary(order, price);
}A service may create a linked token when it owns an additional shutdown or time-budget signal. It must dispose the linked CancellationTokenSource after the owned operation has finished using it. Disposal releases resources; it does not request cancellation or wait for work to stop. Do not dispose a source concurrently with other operations on it.
Propagate without changing meaning
Use the same token for work that belongs to the caller's operation. Do not replace it with CancellationToken.None merely to make a failing test pass. Conversely, cleanup that must complete after cancellation may need its own short, explicitly documented token.
Avoid catching OperationCanceledException as a general failure. A useful boundary pattern is:
try
{
await handler.HandleAsync(request, requestAborted);
}
catch (OperationCanceledException) when (requestAborted.IsCancellationRequested)
{
// Client disconnected or canceled. Record at an appropriate level.
throw;
}For application reporting, identify whether an expected source requested cancellation rather than mislabeling an unrelated timeout or library bug. This is not a runtime task-state rule: an OperationCanceledException escaping an async Task method marks its task canceled even if the exception's token is not canceled.
CPU-bound loops must observe the token
Token-aware I/O APIs observe cancellation while awaiting. CPU-bound work needs explicit checkpoints:
for (var i = 0; i < records.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
Transform(records[i]);
}Check often enough to respond promptly, but not on every microscopic operation when the check itself would distort a hot loop.
Interview traps
- A token is a value that refers to shared cancellation state; disposing the token itself is not required.
- Only the source can request cancellation.
- Cancellation does not automatically undo completed side effects.
- If a database write committed before cancellation, the system needs idempotency or compensation—not wishful rollback.
- Public async APIs normally put the token last.
Review checklist
Trace one request from controller to database and remote HTTP calls. At each await, ask whether cancellation is supported, whether stopping is safe, and which component owns the token. A strong design makes that ownership visible instead of scattering new CancellationTokenSource() throughout the code.
Failure modes
new CancellationTokenSource()deep inside a service with no link to the caller's token. The request is aborted, but the work keeps running.- Forgetting to dispose a linked or timed source. A linked source registers callbacks on its parent tokens. If you never dispose it, those registrations live as long as the parent token, which can mean the whole application.
- One
catch (OperationCanceledException)for everything. Timeouts get logged as client disconnects, and nobody looks at the slow dependency. - Passing
CancellationToken.Noneto make a test pass. The production path loses cancellation.
Classify a cancellation from evidence
Write your predictions before opening the checks below.
- A handler links
requestAbortedwith a 2-second budget. The dependency throwsOperationCanceledExceptionafter 2 seconds while the client is still connected. How should it be classified?
- Who should dispose a linked
CancellationTokenSource?
- A loop checks the token every 50,000 items, and each item takes 2 µs. What is the worst-case delay before it stops?
- A payment was written, and then the request was cancelled. Does cancellation roll it back?
Pause here. Keep the result and the reason separate.
Hint: Read the original sources, then apply a declared precedence. Elapsed time is not source identity.
Compare with the contract
- If the budget source actually reports cancellation and
requestAborteddoes not, classify it as a service timeout. Elapsed time alone is not enough: an unrelatedOperationCanceledExceptionmust not automatically become a timeout.
- The code that created it, normally with
using. Callees only receive the token.
- About 100 ms of processing time (50,000 × 2 µs), assuming a constant per-item cost. Scheduling pauses, blocking work, and cleanup can increase wall-clock latency; this is not a hard real-time bound.
- No. Committed side effects need idempotency or compensation.
Check the boundary
Both caller and budget sources are canceled when the handler catches an OperationCanceledException. What can those current flags establish?
Show answer
Correct answer: B
The current flags do not recover a unique chronological cause. The example’s filters prioritize caller cancellation when both are set; that is a policy, not proof of which event happened first.
Hint: Separate observed state from historical ordering.
TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·