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.
using var cts = new CancellationTokenSource(); cts.Cancel(); cts.Token.ThrowIfCancellationRequested(); // throws OperationCanceledException
Try it
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.
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
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 justTaskCanceledException. Different APIs throw different ones, andThrowIfCancellationRequestedthrows 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 awhen (!token.IsCancellationRequested)filter or catch the cancellation first. - Timeouts look the same.
HttpClienttimeouts throwTaskCanceledExceptiontoo. Checktoken.IsCancellationRequestedto 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()overif (token.IsCancellationRequested) return;when the caller needs to know the work did not complete. - Aggregate wrapping. Blocking waits (
task.Wait()) wrap it in anAggregateException;awaitthrows it directly. - Cleanup still runs.
finallyblocks andusingdisposal execute while the exception unwinds.
Related
- AggregateException, Exception filters, Task, Cancellation, Task.Delay
- Lessons: Cancellation, Tasks