Skip to content

Cancelling a Task

Question

How can you cancel a task?

Short interview answer

Use CancellationTokenSource to signal cancellation and pass its CancellationToken into operations that support it. Cancellation is cooperative: the operation must observe the token and stop.

Detailed answer

Calling Cancel() does not forcibly terminate arbitrary code. The operation checks the token, often by calling ThrowIfCancellationRequested, and returns or throws OperationCanceledException. Propagate tokens through the call chain, dispose the source when appropriate, and distinguish cancellation from faults in the caller's handling.

For example, create a CancellationTokenSource for a request, pass source.Token to the downstream call, and call source.Cancel() when the user leaves the screen. The downstream operation must observe that token; cancellation is cooperative.

Sources