Behavior of setting ConfigureAwait and SynchronisationContext
-
21-12-2019 - |
Question
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 await
ing 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?
Solution
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)
.
OTHER TIPS
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.