According to an article in MSDN Magazine, it is the best practice to "Use ConfigureAwait(false)
when you can." Furthermore it states, "If you can use ConfigureAwait
at some point within a method, then I recommend you use it for every await in that method after that point." Stephen Cleary, the author of that article, states on his blog that "In your 'library' async methods, use ConfigureAwait(false) wherever possible [emphasis added]."
Given that most or all of my await
statements in a library project that is meant to be widely used should have .ConfigureAwait(false)
is it possible to do something/change a setting to make it so that the default behavior of await within my project/dll is to not continue on the a captured context? That is, so that I could omit all the calls to .ConfigureAwait(false)
and instead add .ConfigureAwait(
true
)
only when I need the context to be preserved.
As a general rule, every piece of code that is not in a view model and/or that does not need to go back on the main thread should use ConfigureAwait false. This is simple, easy and can improve the performance of an application by freeing the UI thread for a little longer.
In this video we answer the ever popular question “Which do I use, ConfigureAwait True or False?”. The direct answer to this question is: – If you are a writing code for the UI, use ConfigureAwait(true).
Is it ok to use ConfigureAwait(false) only on the first await in my method and not on the rest? In general, no. See the previous FAQ. If the await task.
The exception here is app-level code, such as Windows Forms, WPF, and ASP.NET. ConfigureAwait(true) corresponds to the default behavior and does nothing meaningful, therefore such calls can be safely omitted.
No, there is no option for this. The Microsoft team did consider a compiler setting or something for that behavior, but ended up rejecting it.
The main reason is that it's quite difficult to tell how the code behaves without knowing how the compiler switch is set.
There is now a third party library that supports this. The ConfigureAwait.Fody Nuget package allows you to use a ConfigureAwait
attribute to mark a class, assembly or method such that all awaits should be .ConfigureAwait(false)
. The project page has this example usage:
using Fody;
[ConfigureAwait(false)]
public class MyAsyncLibrary
{
public async Task MyMethodAsync()
{
await Task.Delay(10);
await Task.Delay(20);
}
public async Task AnotherMethodAsync()
{
await Task.Delay(30);
}
}
I have not tried this myself, but given what I know about how Fody add-ins work, it is certainly possible.
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