Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ConfigureAwait(false) and omitting await?

Tags:

c#

async-await

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.

like image 572
lekroif Avatar asked Aug 03 '14 05:08

lekroif


2 Answers

Is there a difference in functionality between the following two invocations:

  1. DoWorkAsync();
  2. 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:

  1. When the code after this line executes. If you 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.
  2. How exceptions are handled. If you 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).
like image 164
Stephen Cleary Avatar answered Oct 12 '22 20:10

Stephen Cleary


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

like image 37
Jonathan Allen Avatar answered Oct 12 '22 19:10

Jonathan Allen