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
