liveBook · Manning

TaskCanceledException

As explained in C# Concurrency: Asynchronous and multithreaded programming

TaskCanceledException is a .NET exception indicating that an operation represented by a Task was canceled.

TaskCanceledException signals that a Task was completed in the Canceled state. Awaiting it, reading Result, or calling Wait throws this exception, while Task.Exception remains null and IsFaulted is false. section 10.1 section 10.7

TaskCompletionSource<T>.TrySetCanceled transitions its Task to Canceled; passing a cancellation token preserves it through TaskCanceledException.CancellationToken. Check Status or IsCanceled when cancellation is expected. section 10.1 section 10.7

Prefer the race-safe completion pattern:

  • Use TrySetCanceled rather than SetCanceled when multiple threads might complete the Task. section 10.1
  • Use RunContinuationsAsynchronously when completing a Task while holding a lock. section 10.7
  • Distinguish cancellation from faults: cancellation leaves Exception null, whereas TrySetException creates a faulted Task. section 10.1
Listing 10.4 TaskCompletionSource.TrySetCanceled demo
public class TaskCompletionSourceDemo
{
   private Task<int> BackgroundWork()
   {
      var tcs = new TaskCompletionSource<int>();
      Task.Run(()=>
      {
          tcs.TrySetCanceled()                            #1
      });
      return tcs.Task;
   } 
 
   public async Task RunDemo()
   {
       var result = await BackgroundWork();               #2
       Console.WriteLine(result);
   }
}

Shows a minimal TaskCompletionSource workflow that cancels background work and observes the exception through await. section 10.1

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains state transitions, exception properties, token propagation, completion races, and continuation scheduling.
Examples
Demonstrates TaskCompletionSource.TrySetCanceled with await and contrasts TrySetCanceled with SetCanceled.
What it assumes
Assumes familiarity with Tasks and await while teaching cancellation state, exception behavior, and TaskCompletionSource completion.
What you can do after
Diagnose canceled Tasks by inspecting IsCanceled and Status, then complete TaskCompletionSource instances safely.
How it connects
Connects TaskCanceledException with Task, TaskCompletionSource, cancellation tokens, and asynchronous continuations.

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.