Skip to content

ThrowIfCancellationRequested

Context: ThrowIfCancellationRequested checks if the token has been cancelled and, if so, throws an OperationCanceledException.

using System.Threading;
public class Example
{
public void Work(CancellationToken token)
{
token.ThrowIfCancellationRequested(); // throws if cancelled
// More work...
}
}
if (token.IsCancellationRequested)
{
// cleanup before throwing
token.ThrowIfCancellationRequested();
}

Responsive UI: Cancel a long‑running operation when the user clicks a “Cancel” button.

Example: Cancellation in managed threads