When to Use ConfigureAwait() in Asp.net Core 3.1 Code
Question: What is ConfigureAwait(true) in Asp.Net Core 3.1 C#, I have noticed the compiler recommending me to use ConfigureAwait(true) or ConfigureAwait(false).
Answer: According to Microsoft's Developer Blog using ConfigureAwait(false) is recommended as the C-Sharp Compiler finds an awaiter (a line of code with an await directive specified) and continues executing the code on the Original Thread while awaits for a response from another function.
When the response completed, the async function won't notify the awaiter on the Main Thread but will provide the response data on a different thread, leaving the Original/Main Thread undisturbed.
For example, if the response expected from the function call is not awaited by another function somewhere in the application code, use ConfigureWait(true) or rather use _ = functionName(Parameter).ConfigureAwait(true);
Edit this Article
- While developing keep in mind that every time you access the Main Thread Statics there is a cost involved. Therefore, make sure that every time you access the Main Thread it is needed.
When are you suppose to use ConfigureAwait(true)?
- According to Microsoft Blog, the ConfigureAwait(true) is only used in the context of specifying whether the Compiler should await the response or not. In short, if you don't use ConfigureAwait(false) then you can choose to specify ConfigureAwait(true) or not.
The default of the application code is ConfigureAwait(false). If you don't specify ConfigureAwait(false), you will see several warnings when debugging the application.
When using await and then violates the execution by Configuring ConfigureAwait(false), then an error might occur. In some other words, if you use ConfigureAwait(true) unnecessary call back to the Main Thread might occur, remember calling the Original Thread halts execution of code.
Every time the notification is received, the execution of code stops to process the notification. None the less, configuring ConfigureAwait(false) avoids that unnecessary notification to the Main Thread.
- I also found out that, if you are calling an Async Task function in a none Async function for example in an Event Handler, you can easily utilize the Await (More like awaiting for a function to execute, that would normally require a parent function to by an Async function) by ConfiguringAwait(true) or ConfigureAwait(false), this way you have control of the outcome from the function.
References: Microsoft dev blog