🔧 The CancelAfter Timer That Never Gets a Chance to Fire
CancellationTokenSource.CancelAfter schedules an internal timer that calls Cancel once its delay elapses, but that timer belongs entirely to the CancellationTokenSource instance that scheduled it. Disposing the source before the delay elapses tears the timer down along with everything else the source owns, so the scheduled cancellation silently never happens. Any operation still waiting on that source’s token keeps waiting exactly as long as it would have without a timeout at all, because the mechanism meant to cut it off was dismantled before it ever got the chance to run.
🔎 The Problem
async Task<string> CallWithTimeoutAsync(HttpClient client, string url)
{
using var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(30));
// An earlier guard clause returns before the actual call - e.g.
// a cache hit short-circuits the method entirely:
if (TryGetCached(url, out var cached))
return cached; // 'using' disposes cts HERE, cancelling nothing
// If we DO reach this line, the CancelAfter timer is still fine -
// the bug only bites on the early-return path, intermittently.
return await client.GetStringAsync(url, cts.Token);
}
✅ Fix: Create and Dispose the Source Right Around the Call It Times
- Create the CancellationTokenSource, and call CancelAfter, only immediately before the specific operation it’s meant to time out – not earlier in the method, where an unrelated early return can dispose the source before the timed call has even started.
- When a timeout token has to be combined with an already-existing one, use CancellationTokenSource.CreateLinkedTokenSource and keep that linked source alive for the whole duration of the awaited call, disposing it in a finally block placed right after the await rather than relying on a using declared several lines above a possible early exit.
- Make reviewing every path between a CancelAfter call and the operation it times a habit: any return, throw, or continue on that path can dispose the source early on a path that looks completely unrelated to timeouts.
⚠️ Why This Is Easy to Miss
- The bug is entirely path-dependent: the common, fast path – the early return – is exactly the one that disposes the timer early, while the slower path that actually needs the timeout is the one least often exercised during testing.
- Nothing throws when this happens – CancelAfter on a source that gets disposed before its delay elapses simply never gets the chance to run its timer callback, so the operation just hangs for however long the underlying call’s own default timeout, if it has one at all, happens to take, which is often far longer than the 30 seconds that was intended.
A cancellation you schedule and then dispose before it can fire was never actually scheduled at all.

