đź”§ C#: Fix a Custom Awaiter Resuming on the Wrong Thread Context
A hand-rolled custom awaitable has to replicate the thread-context capturing that Task‘s own awaiter already does for you — if its OnCompleted method just stores the continuation and invokes it directly from whatever background callback completes the operation, instead of capturing SynchronizationContext.Current and posting the continuation back through it, every await on that awaitable effectively becomes ConfigureAwait(false) whether the caller wanted that or not.
🔎 The Problem
public void OnCompleted(Action continuation)
{
_continuation = continuation;
// later, called from a background I/O thread:
_continuation?.Invoke(); // resumes on whatever thread completed the op,
} // never the original calling context
âś… Fix: Capture the Context in OnCompleted and Post Back Through It
- Capture
SynchronizationContext.CurrentinsideOnCompleted, at the moment the continuation is registered, and post the continuation back through that captured context when the operation completes, exactly like the built-in task awaiters do. - If the custom awaitable is always meant to behave like
ConfigureAwait(false), document that explicitly on the type, since a caller awaiting it has no other way to know that guarantee doesn’t exist here. - Write a test that awaits the custom awaitable from a context with a non-null
SynchronizationContextand asserts the continuation actually resumes on it, rather than only testing from a console app’s default context, where the difference is invisible.
🚨 Why This Is Dangerous
- UI code that calls into a custom awaitable and assumes it’s back on the UI thread afterward, because every other await in the codebase behaves that way, can throw a cross-thread access exception at the exact line that touches a control — or silently corrupt UI state without throwing at all.
Task’s awaiter remembers where you called it from so you don’t have to — write your own awaiter and that memory is suddenly your job.




