You have the following method:
async Task DoWorkAsync();
Is there a difference in functionality between the following two invocations:
1. DoWorkAsync();
2. await DoWorkAsync().ConfigureAwait(false);
The only one I see, is that Visual Studio gives a warning when using the first one, informing you that method execution will continue without the result being awaited.
Is there a difference in functionality between the following two invocations:
- DoWorkAsync();
- await DoWorkAsync().ConfigureAwait(false);
Yes; they're completely different. The first one starts the asynchronous method and then continues the current method immediately. The second one (asynchronously) waits for the asynchronous method to complete.
There are two major semantic differences:
await DoWorkAsync
, then the following code will not execute until after DoWorkAsync
completes. If you just call DoWorkAsync
without awaiting it, then the following code will execute as soon as DoWorkAsync
yields.await DoWorkAsync
, then any exceptions from DoWorkAsync
will propagate naturally. If you just call DoWorkAsync
without awaiting it, then any exceptions will be silently captured and placed on the returned task (which is ignored, hence the compiler warning).ConfigureAwait(false) says "don't capture the synchronization context". This means that you are still going to await the results, but when it continues it won't try to marshall you back onto the UI thread.
If you are writing a library for other prople to use, always use ConfigureAwait(false) or you may trigger deadlocks.
If you are writing an application that is UI-bound (e.g. WPF, Silverlight, Windows 8) then you should NOT use ConfigureAwait(false) because you'll continue on the wrong thread.
If you are writing an application that is context sensitive (e.g. ASP.NET MVC controllers) then you should NOT use ConfigureAwait(false) because you'll continue on the wrong thread.
reference: http://www.infoq.com/articles/Async-API-Design
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