In a C# async method, what do ThrowIfCancellationRequested, OperationCanceledException and TaskCanceledException do, and how should a caller catch a cancellation?
answer
- Canceled, not Faulted
- a base exception and its subclass
- the builder inspects the exception type
- returning early looks like success
basics
~10 sThrowIfCancellationRequested throws OperationCanceledException once the token is cancelled. An async Task method that ends with that exception completes as Canceled, not Faulted. TaskCanceledException derives from it, so callers catch OperationCanceledException.
solid answer
~40 s`token.ThrowIfCancellationRequested()` throws `OperationCanceledException` carrying that token once cancellation has been requested. When an `async Task` method ends with an `OperationCanceledException`, the method builder completes its task as `Canceled` rather than `Faulted`, and `await` rethrows the exception. APIs such as `Task.Delay` throw `TaskCanceledException`, which derives from `OperationCanceledException`, so a caller writes `catch (OperationCanceledException)` and covers both; catching only `TaskCanceledException` misses the base type. Cancellation is not a failure, so it should not be logged as an error, and a blanket `catch (Exception)` must not swallow it. Returning early with `if (token.IsCancellationRequested) return;` is the trap: the task completes as `RanToCompletion` and the caller believes the import finished.
code
csharp · 28 linesusing var cts = new CancellationTokenSource();
cts.Cancel(); // the user has already clicked Cancel
Task thrown = ImportThrowingAsync(cts.Token);
Task returned = ImportReturningAsync(cts.Token);
try { await thrown; }
catch (OperationCanceledException ex) { Console.WriteLine($"await rethrew {ex.GetType().Name}"); }
await returned;
Console.WriteLine($"thrown: {thrown.Status}, returned: {returned.Status}");
try { await Task.Delay(1000, cts.Token); }
catch (OperationCanceledException ex) { Console.WriteLine($"Task.Delay threw {ex.GetType().Name}"); }
try { thrown.Wait(); }
catch (AggregateException ex) { Console.WriteLine($"Wait threw AggregateException of {ex.InnerException!.GetType().Name}"); }
static async Task ImportThrowingAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(10, CancellationToken.None);
}
static async Task ImportReturningAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested) return; // the caller cannot tell this from success
await Task.Delay(10, CancellationToken.None);
}go deeper
Recall that cancelled code throws OperationCanceledException and that callers catch that base type.
Explain why an async method's task ends Canceled rather than Faulted, why Task.Delay throws the subclass, and why returning early misleads the caller.
Show where checkpoints belong around side effects, how catch order and filters keep cancellations out of error telemetry, and how Task.Run differs.
Decide how a codebase separates expected cancellations from real failures in logs, retries and alerts, and how that rule is enforced in review.
## Throwing is how cancelled code says it stopped A cancellation token only carries a request. The code that honours it has to **end in a way the caller can see**, and in .NET that way is an exception: **`OperationCanceledException`** (namespace `System`). The helper `CancellationToken.ThrowIfCancellationRequested()` is a one-liner for the common case: if the token's `IsCancellationRequested` is true, it throws a new `OperationCanceledException` whose `CancellationToken` property is that token; otherwise it does nothing. ## What the task records An `async Task` or `async Task<T>` method never lets an exception escape directly to its caller; the compiler-generated builder stores it in the returned task. The builder treats one exception type specially. In the runtime's `AsyncTaskMethodBuilder<TResult>.SetException`, an exception that `is OperationCanceledException` makes the builder call `TrySetCanceled(oce.CancellationToken, oce)`; anything else goes to `TrySetException`. The result: | How the method ends | `Task.Status` | What `await` throws | What `.Wait()` throws | |---|---|---|---| | returns normally | `RanToCompletion` | nothing | nothing | | throws `OperationCanceledException` | `Canceled` | the same `OperationCanceledException` | `AggregateException` wrapping a `TaskCanceledException` | | throws any other exception | `Faulted` | that exception | `AggregateException` wrapping it | Two details are easy to miss: - In an `async` method the status is `Canceled` whichever token the exception carries, even one that was never requested. `Task.Run` with a synchronous delegate, and the other task factories, are stricter: there, an `OperationCanceledException` marks the task `Canceled` only when it carries the token the task was created with and that token has been cancelled; otherwise the task is `Faulted`. (An `async` lambda passed to `Task.Run` is an async method, so the first rule applies to it.) - `await` rethrows the stored exception unchanged, so the caller sees the exact type the method threw. Blocking with `.Wait()` or `.Result` wraps a fresh `TaskCanceledException` in an `AggregateException` instead. ## OperationCanceledException vs TaskCanceledException `TaskCanceledException` derives from `OperationCanceledException`. BCL methods that complete a task as cancelled, such as `Task.Delay(ms, token)`, surface it, and awaiting a task that was cancelled without a stored exception produces one too. Your own code calling `ThrowIfCancellationRequested()` produces the base type. A caller cannot know which one a deep call chain will produce, so: 1. Catch **`OperationCanceledException`**. It covers both types. 2. Put that catch **before** any `catch (Exception)`, or add a filter such as `catch (Exception ex) when (ex is not OperationCanceledException)`, so a generic error handler does not report a user's Cancel click as a crash. 3. Treat it as an expected outcome: update the UI to "Import cancelled", log it at information level if at all, and do not retry. ## Returning early hides the cancellation It is tempting to write `if (cancellationToken.IsCancellationRequested) return;` inside the import loop. That ends the method **normally**, so its task is `RanToCompletion`, the caller's `await` succeeds, and the code after it reports "Import complete" for a half-imported batch. Returning early is acceptable only when the method's contract genuinely allows partial results and says so, for example by returning how many files were done. Otherwise, throw. ## Where checkpoints go - Call `ThrowIfCancellationRequested()` **before** a step with a side effect (writing a row, moving a file), so a cancelled import does not start one more irreversible step. - In a CPU-bound loop, check every few hundred or thousand iterations rather than every iteration if the body is tiny. - Async I/O calls that accept the token check it themselves; do not wrap each of them in an extra check. - Cleanup still runs: `finally` blocks and `using` declarations execute as the exception unwinds, which is where temporary files are deleted. ## Where this leaf stops The order and filters of `catch` clauses in general, and `throw` vs `throw ex`, are covered with exception handling; how `async void` methods crash the process, and `Task` vs `void` returns, are covered with task-based methods. How `Task.WhenAll` reports several cancelled or failed tasks is covered with task combinators.
- In C#, does Task.Run mark a task Canceled when its synchronous delegate throws OperationCanceledException?Only under a condition. The task ends `Canceled` when the exception carries the same token that was passed to `Task.Run` and that token has been cancelled. If no token was passed, or the exception carries a different one, the task ends `Faulted` and awaiting it still throws the `OperationCanceledException`. A token passed to `Task.Run` that is already cancelled also stops the delegate from starting at all.
- In a C# import, how do you keep a catch (Exception) error handler from reporting a user's Cancel click as a failure?Put a `catch (OperationCanceledException)` clause before it, or filter the general clause with `when (ex is not OperationCanceledException)`. Some teams also check the specific token, `when (cancellationToken.IsCancellationRequested)`, so that an `OperationCanceledException` from an unrelated source, such as a library's internal timeout, is still treated as a failure.
- Catches only TaskCanceledException and misses OperationCanceledException from ThrowIfCancellationRequested
- Returns early on cancellation so the caller reports a half-done import as complete
- Logs every cancellation as an error and pages someone about a user's Cancel click
- Believes an async method that throws OperationCanceledException produces a Faulted task
- Lets a catch (Exception) block before the cancellation catch swallow the cancellation