I have been using async
/await
for a while, but delved deeper recently, and read a lot of best practice tips saying to by default always use ConfigureAwait(false)
to prevent deadlocks and improve performance.
I just want to make sure I am not missing something when I presume this only applies when the is an actual current SynchronizationContext
or TaskScheduler
in play, correct?
If I have a Windows service app that is responding to messages/commands/etc. asynchronously, it always just uses the default scheduler = probably the same threadpool thread that the awaitable completed on will execute the continuation, thus no deadlock and no performance difference can be had from using ConfigureAwait(false)
, correct?
It's not like I can't put it there, but I hate noisey code so much...
NET Core you won't need to spread ConfigureAwait(false) all over your code. Almost! This is almost true, it is still recommended the utilization of ConfigureAwait(false) for libraries as a fallback if those libraries are used within a legacy framework. But for most of the cases yes, in .
False. It's needed when running on . NET Core for exactly the same reasons it's needed when running on . NET Framework.
In the code that relies on the asynchronous programming model ( async / await keywords), ConfigureAwait() calls are often used to manage the synchronization context. The way ConfigureAwait() calls work and their usage scenarios are explained in detail in this Microsoft .
A situation to use ConfigureAwait(true) is when performing await in a lock, or using any other context/thread specific resources. This requires a synchronization context, which you will have to create, unless you are using Windows Forms or WPF, which automatically create a UI synchronization context.
In general, this is true. When working in a Console or Service scenario, there is no SynchronizationContext
installed (by default) so the continueOnCapturedContext
option in ConfigureAwait
will have no effect, which means you can safely remove it without changing the runtime behavior.
However, there can be exceptions, so I would often suggest writing your code including ConfigureAwait(false)
when appropriate anyways.
The main advantages of including this even in a console or service application are:
SynchronizationContext
while running, the behavior of your methods won't change.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With