Cancellation and failure
Cancellation and failure
Cancellation is a cooperative request to stop unnecessary work. A CancellationTokenSource owns the request; a CancellationToken communicates it. A task may complete successfully, fault or be canceled, and callers should preserve these outcomes rather than treating every exception as cancellation.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. File examples require an authorized disposable environment with a writable temporary directory and no concurrent writers.
Observe an explicit cancellation request
Pass a token into operations and check it at appropriate boundaries. ThrowIfCancellationRequested reports cancellation through OperationCanceledException. A token is not a command that forcibly stops a thread.
using System;using System.Threading;using System.Threading.Tasks;using var source = new CancellationTokenSource();source.Cancel();Task<int> task = CountAsync(source.Token);try { Console.WriteLine(await task); }catch (OperationCanceledException) { Console.WriteLine("Canceled"); }Console.WriteLine(task.IsCanceled);static async Task<int> CountAsync(CancellationToken token){ await Task.CompletedTask; token.ThrowIfCancellationRequested(); return 4;}The async method observes the requested cancellation before returning a result. The task records cancellation.
Expected output (reasoned, not executed):
CanceledTrueHandle faults separately
Awaiting a faulted task propagates an exception to the await site. Use specific exception handling when recovery is possible; do not silently discard a failure. The following fixture has a single known fault.
using System;using System.Threading.Tasks;Task<int> task = Task.FromException<int>(new InvalidOperationException("Stock unavailable"));try { Console.WriteLine(await task); }catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }Console.WriteLine(task.IsFaulted);A known operational error is not cancellation; the task is faulted and the message is synthetic.
Expected output (reasoned, not executed):
Stock unavailableTruePass cancellation to I/O and preserve cleanup
Async file APIs accept a cancellation token. A pre-canceled token is a deterministic way to demonstrate canceled reads of a known file. Keep the token source alive until operations finish, and clean up owned resources even on cancellation.
using System;using System.IO;using System.Threading;var folder = Directory.CreateTempSubdirectory("bytemind-");string path = Path.Combine(folder.FullName, "note.txt");try{ File.WriteAllText(path, "Ready"); using var source = new CancellationTokenSource(); source.Cancel(); try { Console.WriteLine(await File.ReadAllTextAsync(path, source.Token)); } catch (OperationCanceledException) when (source.IsCancellationRequested) { Console.WriteLine("Read canceled"); }}finally { File.Delete(path); folder.Delete(); }Console.WriteLine("Cleanup finished");The read receives a token already marked canceled. The finally block removes only the owned fixture and then execution continues.
Expected output (reasoned, not executed):
Read canceledCleanup finishedCommon mistakes and edge cases
Cancellation may arrive after an operation succeeds, and a token may be ignored by an API. A canceled write may have partially changed its destination, so cancellation is not rollback. Catch only the expected cancellation when appropriate, preserve unexpected faults, and avoid using .Wait() or .Result as a substitute for await. Timeouts and retry budgets are follow-up material. A linked cancellation source can observe either a caller token or a local stop token; canceling it does not cancel its parents. Dispose the linked source after its users complete. Disposing a source is not a request to cancel. A cancellation callback registered after cancellation can run immediately; a registration has its own disposable lifetime.
Practice and recap
For a CountAsync call with an uncanceled token, a pre-canceled token, and a separate Task.FromException<int> fault, predict which task state and result or exception each caller observes.
Hint: Separate success, cancellation and fault.
Learning objective: Propagate cancellation and distinguish it from fault. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cancellation and failure — knowledge check
Apply the lesson concepts to the following scenarios.
What does CancellationTokenSource.Cancel do?
What does ThrowIfCancellationRequested do after a request?
How does a known InvalidOperationException from a task appear?
Why pass the token into ReadAllTextAsync?
Does canceling a write guarantee the old file remains intact?