TaskCompletionSource
Question
Describe
TaskCompletionSourceand when it can be useful.
Short interview answer
TaskCompletionSource<T>lets code manually complete aTask<T>with a result, exception, or cancellation. Use it to adapt callback- or event-based APIs to the task-based asynchronous pattern.
Detailed answer
For example, an API may signal completion through an event rather than return a task. A TaskCompletionSource<T> can complete when that event arrives, allowing callers to await it. Use TrySetResult, TrySetException, or TrySetCanceled when multiple paths may race. Prefer existing task-based APIs when available, and consider asynchronous continuations to avoid running user continuations unexpectedly on the completion thread.
For example, an adapter around a callback-only API can complete a TaskCompletionSource<Result> from its success callback and complete it with an exception from its error callback, allowing callers to use await instead of registering their own callbacks.