I was having a problem with a hanging await (described here). During research I found out that calling SetResult
on my TaskCompletionSource
actually invokes awaiting continuation in the context of the thread that called SetResult
(this is also spelled out in this answer to a somewhat related question). In my case this is a different thread (a thread-pool worker thread) from the one that started the await (an ASP.NET request thread).
While I'm still not sure why this would cause a hang, I decided to try forcing the SetResult
into the original context. I stored the value of SynchronizationContext.Current
before entering await on the request thread and manually applied it in the worker thread via SynchronizationContext.SetSynchronizationContext
just before calling SetResult
. This solved the hang and I can now await all my async methods without having to specify ConfigureAwait(false)
.
My question is: is this a reasonable and correct approach to manually capturing and applying the SynchronizationContext
? FWIW, I tried doing a simple Post()
with the SetResult
delegate first, but that still caused a hang. I'm obviously a bit out of my comfort zone here... Please help me understand what's going on!