C# Reference ยท Async and Concurrency
TaskCompletionSource
Reference for TaskCompletionSource<T> in C#: create a Task you complete manually with SetResult, SetException or SetCanceled, and wrap callbacks and events.
TaskCompletionSource<TResult> creates a Task<TResult> that is not tied to any running code. You hold the controlling object and decide when and how the task finishes: with a result, an exception, or cancellation. Anyone who awaits tcs.Task is resumed when you complete it.
That makes it the standard bridge between callback-based or event-based APIs and async/await: you start the old-style operation, return tcs.Task, and complete it from the callback. A non-generic TaskCompletionSource (since .NET 5) exists for operations without a result.
var tcs = new TaskCompletionSource<int>(); Task<int> task = tcs.Task; tcs.SetResult(42); // task is now completed, awaiters resume
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class TaskCompletionSource<TResult> { public TaskCompletionSource(); public TaskCompletionSource(object? state); public TaskCompletionSource(TaskCreationOptions creationOptions); public TaskCompletionSource(object? state, TaskCreationOptions creationOptions); public Task<TResult> Task { get; } public void SetResult(TResult result); public void SetException(Exception exception); public void SetException(IEnumerable<Exception> exceptions); public void SetCanceled(); public void SetCanceled(CancellationToken cancellationToken); public bool TrySetResult(TResult result); public bool TrySetException(Exception exception); public bool TrySetCanceled(); }
| Name | Description |
|---|---|
Task |
The task controlled by this object. Hand it out to callers. |
SetResult |
Completes the task successfully (RanToCompletion). |
SetException |
Completes the task as Faulted with the given exception(s). |
SetCanceled |
Completes the task as Canceled. |
TrySet* |
Same as the Set* methods but return false instead of throwing when already completed. |
creationOptions |
RunContinuationsAsynchronously is the important one. |
Errors: a Set* method throws InvalidOperationException if the task is already completed. Use TrySet* when several code paths may race to finish it (for example completion versus timeout).
Usage notes
- Always consider
TaskCreationOptions.RunContinuationsAsynchronously. By default, continuations may run synchronously insideSetResult, on your thread, while you hold locks or are in the middle of other work. That causes surprising re-entrancy and sometimes deadlocks. The option queues them instead. Since .NET 5 it is cheap to use. - Complete exactly once, on every path. If the callback never fires (timeout, error, disposal), callers wait forever. Guard with a timeout or a
CancellationTokenand callTrySetCanceled. - Do not expose the
TaskCompletionSourceitself, only itsTask. Otherwise consumers could complete it. - Do not use it to wrap synchronous work. For a value you already have, use
Task.FromResult; for CPU work,Task.Run. - Cancellation support: register
token.Register(() => tcs.TrySetCanceled(token))and dispose the registration when the operation ends. - Faulted tasks must be observed. If
SetExceptionis used and nobody awaits the task, the exception is silently ignored (it no longer crashes the process), but you lose the error. - Testing: a
TaskCompletionSourceis a good way to control timing in unit tests: the code under test awaitstcs.Task, and the test decides when to release it.
Related
- Task, async and await, Cancellation, ValueTask
- Lessons: Tasks, Async and await, Cancellation