TaskCompletionSource.TrySetException completes its associated Task as faulted and stores one or more exceptions for later observation. Awaiting the task, reading Result, or calling Wait observes the failure; Task.Exception contains the stored AggregateException. section 10.7 section 10.1
Use the method with these safeguards:
- Check its Boolean result: true means this call completed the task; false means another completion already won. section 10.7
- Prefer TrySetException over SetException when multiple threads might complete the source, because SetException can fail under a race. section 10.7
- Avoid calling it while holding a lock unless the source uses RunContinuationsAsynchronously; continuations can otherwise run inside the call. section 10.7
Propagating background initialization failure
A background initializer catches its calculation exception and calls tcs.TrySetException(ex). Consumers await the exposed task, receiving the value on success or the initialization failure on error, without separately coordinating readiness and error reporting. section 10.3
Listing 10.3 TaskCompletionSource.TrySetException demo
public class TaskCompletionSourceDemo
{
private Task<int> BackgroundWork()
{
var tcs = new TaskCompletionSource<int>();
Task.Run(()=>
{
tcs.TrySetException(new Exception("oops")) #1
});
return tcs.Task;
}
public async Task RunDemo()
{
var result = await BackgroundWork(); #2
Console.WriteLine(result);
}
}
Runnable template showing a TaskCompletionSource completed with TrySetException and awaited by the caller. section 10.1
