Search code examples
c#azureasync-awaitconfigureawait

Is ConfigureAwait(false) required on all levels of the async chain when no real I/O call is involved?


Implementing a reusable adaptor type of library on top of Azure Document Db Client SDK.

The library can run anywhere, not only in an ASP.NET Core web service, but in a command line app, ASP.NET Web Api etc.

In this library all methods are async and they are simply layers of abstraction that makes it easier to use Document Db client api s. The only real async call - I/O request - is actually done on the lowest layer by the api s from the Document Db SDK. Any code above that I wrote is just in memory data transformations, conversions, no actual I/O call is involved but they are all async as well since the lowest layer Document Db api s are async.

Do I still need to use ConfigureAwait(false) on all layers of upper level code in the stack, or is that enough to only call ConfigureAwait(False) on the lowest layer of my own code that calls Document Db SDK s methods which make the real I/O call ?


Solution

  • The continuations unlike a synchronous code which precedes an await call, are executed in context of different call-stack calls. In particular they are scheduled for execution as separate delegates and there is no call-stack relationship between them. So specifying ConfigureAwait(false) for very last continuation execution will take effect only for this specific continuation, other continuations will still execute using their individual scheduling configuration. That is, if your goal is to ensure not capturing a synchronization context by any continuation in your library (in order to prevent potential dead locks or any other reason) then you should configure all await calls which have continuations with ConfigureAwait(false).