Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Exceptions and Diagnostics

The OperationCanceledException class

Reference for OperationCanceledException in C#: how cancellation tokens throw it, how TaskCanceledException differs, how to catch it and how to avoid swallowing it.

System.OperationCanceledException signals that an operation stopped because somebody asked it to, usually through a CancellationToken. It is not an error in the usual sense: the caller wanted the work to stop, and the exception is the way the work unwinds its call stack cooperatively.

Methods throw it when you call token.ThrowIfCancellationRequested() or when a library API such as Task.Delay, HttpClient.GetAsync or Stream.ReadAsync observes a canceled token. TaskCanceledException is a subclass thrown by task-based APIs. The exception carries the CancellationToken in its CancellationToken property.

C#
using var cts = new CancellationTokenSource();
cts.Cancel();
cts.Token.ThrowIfCancellationRequested(); // throws OperationCanceledException

Try it

C# Canceling a delay

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Cooperative cancellation and task status

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public class OperationCanceledException : SystemException
{
    public OperationCanceledException();
    public OperationCanceledException(string? message);
    public OperationCanceledException(CancellationToken token);
    public OperationCanceledException(string? message, CancellationToken token);
    public OperationCanceledException(string? message, Exception? innerException);

    public CancellationToken CancellationToken { get; }
}

public class TaskCanceledException : OperationCanceledException
{
    public Task? Task { get; }
}
Name Description
token The token whose cancellation caused the exception. Exposed through CancellationToken.
message Optional description.
Task On TaskCanceledException: the canceled task, if any.

Errors / undefined behavior: none for the exception itself. When a task throws OperationCanceledException with the same token that was passed to Task.Run or StartNew, the task ends in the Canceled state; with another token (or none) it ends as Faulted.

Usage notes

  • Catch OperationCanceledException, not just TaskCanceledException. Different APIs throw different ones, and ThrowIfCancellationRequested throws the base type.
  • Do not treat it as a failure. Do not log it as an error and do not retry blindly. A canceled operation usually means "stop quietly".
  • Do not swallow it by accident. A broad catch (Exception) inside a loop turns cancellation into an endless retry. Add a when (!token.IsCancellationRequested) filter or catch the cancellation first.
  • Timeouts look the same. HttpClient timeouts throw TaskCanceledException too. Check token.IsCancellationRequested to tell a caller cancel from a timeout.
  • Cancellation is cooperative. Nothing stops code that never checks the token. Pass the token to every async call and test it in long loops.
  • Prefer ThrowIfCancellationRequested() over if (token.IsCancellationRequested) return; when the caller needs to know the work did not complete.
  • Aggregate wrapping. Blocking waits (task.Wait()) wrap it in an AggregateException; await throws it directly.
  • Cleanup still runs. finally blocks and using disposal execute while the exception unwinds.