🔧 Fix a TaskCompletionSource Never Completing After a Timeout
Bridging a callback-based API into async/await with a TaskCompletionSource works cleanly as long as something eventually calls SetResult or SetException on it, but a manual timeout built with Task.WhenAny(tcs.Task, Task.Delay(timeout)) only decides which task your own code moves on from first — it does nothing to the TaskCompletionSource itself. If the underlying callback-based operation has no cancellation support and never calls back at all, that TCS’s Task sits pending forever, kept alive by whatever’s still referencing it, even though your code has already logically moved on after the delay won the race.
🔎 The Problem
var tcs = new TaskCompletionSource<Result>();
legacyApi.BeginOperation(result => tcs.TrySetResult(result));
var winner = await Task.WhenAny(tcs.Task, Task.Delay(timeout));
if (winner != tcs.Task)
{
// "Timed out" - but tcs.Task is still pending right now, and stays
// pending forever if legacyApi's callback never actually fires;
// nothing here ever calls SetException/SetCanceled on it
✅ Fix: A TaskCompletionSource Never Completing After a Timeout
- Prefer `await tcs.Task.WaitAsync(timeout)` (available since .NET 6) over Task.WhenAny for this pattern — it throws a TimeoutException and, crucially, still leaves you a reference to handle the original task’s eventual completion instead of abandoning it silently.
- Register a CancellationToken callback that calls TrySetCanceled() (or TrySetException) on the TaskCompletionSource directly whenever the operation should be considered timed out, so the task itself actually completes instead of just being out-raced.
- Always construct TaskCompletionSource with TaskCreationOptions.RunContinuationsAsynchronously, so a late completion from the legacy callback doesn’t synchronously run continuations on whatever thread happens to call SetResult.
🚨 Why This Is Dangerous
- A TaskCompletionSource that never completes keeps its continuations and any captured state reachable for as long as something still holds a reference to it, which across enough “timed out” operations in a long-running service adds up to a slow, hard-to-diagnose memory leak.
Racing a timeout against a task decides which one you wait for — it was never going to decide whether the other one actually finishes.




