Lately we had a discussion on when to use ConfigureAwait(true) or ConfigureAwait(false) in ASP.NET Core 2. In the end most of the team, including me, had a faulty assumption on how to do this in ASP.NET Core. In this case ASP.NET Core is different from ASP.NET. Good to know if you have to decide on what to use in ASP.NET core.
When use ConfigureAwait
ConfigureAwait is used in the async/await paradigm or future/promise paradigm. It is used for returning a value in the future, where the value is retrieved asynchronously. ConfigureAwait tell if the result should be continued on the captured context, which is attached to the current thread. In some cases this really matters, because the current context does contain information that is otherwise lost. For example in the case of a UI thread. In that case you can only do UI changes on the UI thread, so you have to return in that context to put the information on the UI. In the case of ASP.NET classic the thread contains the synchronization context that contains the http request context. In many cases you need this to complete the request correctly. So methods that handle the request on the highest level do need to set the
continueOnCapturedContext to true.
However in the case of ASP.NET Core there are many changes over ASP.NET classic. One of them is that the ASP.NET request context is gone. The continueOnCapturedContext should be set to false in a ASP.NET Core application because there is no need to continue on the context. When the call returns there is no need to wait for the thread that started the request, which is good because you have less change on deadlocks and less waiting time.
Default behavior without explicit set of ConfigureAwait
When doing async/await without ConfigureAwait, the call is executed as continueOnCapturedContext is true. Code analysis rule CA2007 will give you a warning that ConfigureAwait is not set. This will help you to decide in all cases if you want to continue on any context or the specific one you where before the call. However if you have no synchronization context the value of continueOnCapturedContext doesn’t matter. There is nothing to synchronize.