0

In his answer Stephen explained that when ConfigureAwait(false) is called the rest of the method will be executed on a thread pool thread unless the Task you're awaiting is already complete.

What is clear: If I use ConfigureAwait(false) everything executed after the asynchronous call will be executed on a thread pool thread and therefore not run in the UI SynchronizationContext, otherwise (escpecially needed for UI based things like textBox1.Text = data.Property) it runs within UI SynchronizationContext.

What I don't understand is: Does await not mean that the Task I am waiting for is always completed before the methods is going on? So how can the Task not be completed before going on?

Community
  • 1
  • 1
Batz
  • 13
  • 2

2 Answers2

2

It's important to understand the precendence order. In particular, the dot operator (.) is of higher priority than await. So, when you do:

await SomeMethodAsync().ConfigureAwait(false);

That's identical to:

var task = SomeMethodAsync();
var awaitable = task.ConfigureAwait(false);
await awaitable;

So, the ConfigureAwait is evaluated before the await expression, which actually does the (asynchronous) waiting.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
1

Imagine something like this

var task = obj.SomeTaskAsync();
// do some lengthy computation
var value = await task.ConfigureAwait(false);

I think it's easy to see that the task could be completed even before the await task call.

In this case the code after the await will be executed in the same context, even if you have used .ConfigureAwait(false).

Dirk
  • 10,668
  • 2
  • 35
  • 49
  • Thank you, Dirk! Ok, alright I got it! Always only imagined on things like `var result = await DoSomething().ConfigureAwait(false);`. But does this not mean if calling something like my example my task is *always* completed before executing the rest of the method and should thereby executed in the UI SynchronisationContext? – Batz Jan 09 '14 at 10:01
  • Yes, but you should not rely on that. If you *want* to use execute the code after `await` on the same context as the call to the async method then don't use `.ConfigureAwait`. – Dirk Jan 09 '14 at 10:03
  • I think it would make more sense to write this code like this: `var task = obj.SomeTaskAsync(); /* do some lengthy computation */ var value = await task.ConfigureAwait(false);` That's because `ConfigureAwait()` makes sense only together with `await`. – svick Jan 09 '14 at 12:02