A deep dive into ConfigureAwait

Nelson Parente
ITNEXT
Published in
5 min readDec 3, 2020

--

Photo by Ricardo IV Tamayo on Unsplash

Alright alright alright! (Yes, its a Matthew McConaughey reference)

As you might already notice, I really like asynchronism and its intrinsics. I love a hard challenge and understanding deeply asynchronism was a challenge.

The beauty of asynchronism is that it can be sweet and bitter at the same time, depending on how you implement it. But, if you understand how it works under the hood and its syntactic sugar do you'll be able to master it and enjoy its full potential.

In my last blogpost, .NET Async Programming in a Nutshell, we looked at some concepts of asynchronism in .NET and the implementation best practices. When we talk about asynchronism in .NET there is one extension method that is almost always present in the discussion, the ConfigureAwait(false).

Do you write .ConfigureAwait(false) after every await usage? If yes, can you explain why? Or this is something that you do mechanically because it's “the pattern”?

Before understanding better the ConfigureAwait(false) we must take a couple of steps back and look at the SynchronizationContext.

SynchronizationContext

Microsoft documentation states that the SynchronizationContext class provides the basic functionality for propagating a synchronization context in various synchronization models. Did you understand what it does from that description? I didn't, so I had to dig deeper into it.

Every running thread has its “current” SynchronizationContext and there is one special method in this class, the Post:

public virtual void Post (System.Threading.SendOrPostCallback d, object? state)

This method in the SynchronizationContext default implementation receives a delegate and calls ThreadPool.QueueUserWorkItem that will be invoked asynchronously. Then the ThreadPool that contains a queue with the work to be done, will callback the result when the Task execution is completed.

Noticed that the Post is a virtual method? A virtual method can be overridden and implemented differently, and that’s what some frameworks actually do, they extend SynchronizationContext and override the implementation of the virtual method. For example, .NET Framework uses…

--

--