CancellationToken patterns; cooperative cancel
Pass and honor CancellationToken: create CTS, poll/throw for cancel, pass to async APIs, and clean up with registrations.
Cooperative cancellation
Aim: Cancel work cooperatively.
- Create a CancellationTokenSource
- Pass CancellationToken down
- Check IsCancellationRequested or call ThrowIfCancellationRequested()
- Honor cancel quickly and cleanly
Caller-driven cancel
Create a CancellationTokenSource, pass the token, and cancel from the caller; the callee throws OperationCanceledException.
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
static async Task WorkAsync(CancellationToken ct)
{
// Poll occasionally; throw to end cooperatively
for (int i = 0; i < 5; i++)
{
ct.ThrowIfCancellationRequested();
Console.WriteLine("Step " + i);
await Task.Delay(100, ct); // pass token to async API
}
}
public static void Main(string[] args)
{
var cts = new CancellationTokenSource();
Task t = WorkAsync(cts.Token);
// Cancel after a short delay (simulated user action)
Thread.Sleep(180);
cts.Cancel();
try
{
t.GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
Console.WriteLine("Canceled!");
}
}
}
All lessons in this course
- CancellationToken patterns; cooperative cancel
- Timeouts, IProgress , async disposables (emulation)
- Resilience basics: retry & backoff