Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

OperationCanceledException — signaling operation cancellation

OperationCanceledException signals that an operation was canceled. Learn how it works with CancellationToken, what ThrowIfCancellationRequested() does, and how requesting cancellation differs from acknowledging it.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

token.ThrowIfCancellationRequested();
throw new OperationCanceledException(token);
catch (OperationCanceledException ex) when (ex.CancellationToken == token && token.IsCancellationRequested) { /* handle expected cancellation */ }

OperationCanceledException in the System namespace signals operation cancellation. Cancellation is cooperative: CancellationTokenSource.Cancel() requests cancellation but does not itself interrupt executing code. The operation must observe the request and stop working.

The preferred checkpoint is token.ThrowIfCancellationRequested(): it throws only when cancellation has been requested and includes the token. This is equivalent to checking token.IsCancellationRequested and executing throw new OperationCanceledException(token);. The exception's CancellationToken property identifies its associated token.

TaskCanceledException derives from OperationCanceledException, so catching the base class covers both types. Handle expected cancellation at an appropriate operation boundary; the example's filter checks both token identity and the cancellation request instead of ignoring every exception of this type.

For Task.Run(..., token) overloads that take a synchronous delegate, if the delegate runs and throws this exception, the task becomes Canceled only if the exception's token matches the supplied token and cancellation was requested on that token. Otherwise, the task becomes Faulted. Returning normally from the delegate produces RanToCompletion.

For a task-returning async delegate, an OperationCanceledException that escapes the delegate can cancel the inner task even if the exception's token differs from the token supplied to Task.Run or cancellation was not requested. The proxy task returned by Task.Run follows the inner task's outcome. The synchronous example demonstrates the mechanism without timing races and requires no preview language features.

Examples

using System;
using System.Threading;

using var source = new CancellationTokenSource();
CancellationToken token = source.Token;
source.Cancel();

try
{
    token.ThrowIfCancellationRequested();
    Console.WriteLine("Completed");
}
catch (OperationCanceledException ex)
    when (ex.CancellationToken == token && token.IsCancellationRequested)
{
    Console.WriteLine("Canceled");
}

Result

Canceled

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources