3 · Reliability and project · 25 MIN
Async, await and cancellation
Await suspends a method without blocking its caller’s thread.
An asynchronous method returns a Task representing work and eventual completion. Cancellation is cooperative: the token must reach an operation that observes it. This example cancels before Task.Delay begins, producing a deterministic cancellation path. In real I/O, cancellation may arrive during work, so cleanup belongs in using or finally where appropriate. Do not call Result or Wait in request handlers to turn async operations into blocking ones. Bounded concurrency is a separate concern covered by the advanced pipeline workshop.
Await the task and preserve cancellation through each layer.
Read the example
using System;
using System.Threading;
using System.Threading.Tasks;
static async Task<int> ReadAsync(CancellationToken ct) {
await Task.Delay(100, ct);
return 42;
}
using var stop = new CancellationTokenSource();
stop.Cancel();
try { Console.WriteLine(await ReadAsync(stop.Token)); }
catch (OperationCanceledException) when (stop.IsCancellationRequested) { Console.WriteLine("cancelled"); }Check the expected output
cancelled
Your challenge
Add one successful call and a separately cancelled call, then propagate the token through an intermediate service method.
Solution cost: O(1) application state per call, excluding the external operation. time · Account for collection storage separately from the returned result. space
Common trap
Receiving a CancellationToken without passing it onward does not cancel downstream work.
Study the project implementation
using System;
using System.Threading;
using System.Threading.Tasks;
static async Task<int> ReadAsync(CancellationToken ct) {
await Task.Delay(100, ct);
return 42;
}
using var stop = new CancellationTokenSource();
stop.Cancel();
try { Console.WriteLine(await ReadAsync(stop.Token)); }
catch (OperationCanceledException) when (stop.IsCancellationRequested) { Console.WriteLine("cancelled"); }Further reading: Official documentation
Next lesson: Project · A tested expense report →