liveBook · Manning

TrySetException

As explained in C# Concurrency: Asynchronous and multithreaded programming

TaskCompletionSource.TrySetException attempts to fault the associated non-generic Task and associate one or more exceptions with it.

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

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains faulting, exception observation, completion races, and continuation safety, but does not descend into runtime implementation internals.
Examples
Demonstrates a TaskCompletionSource.TrySetException call inside Task.Run and a background initializer that catches and forwards exceptions.
What you can do after
Apply it to report asynchronous failures and distinguish successful, faulted, and canceled task completion.
How it connects
Connects TaskCompletionSource, Task, await, AggregateException, continuations, and asynchronous initialization.

Related concepts

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.