I thought I understood the async-wait pattern and the Task.Run
operation.
But I am wondering why in the following code example the await
does not sync back to the UI thread after returning from the finished task.
public async Task InitializeAsync()
{
Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}"); // "Thread: 1"
double value = await Task.Run(() =>
{
Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}"); // Thread: 6
// Do some CPU expensive stuff
double x = 42;
for (int i = 0; i < 100000000; i++)
{
x += i - Math.PI;
}
return x;
}).ConfigureAwait(true);
Console.WriteLine($"Result: {value}");
Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}"); // Thread: 6 - WHY??
}
This code runs within a .NET Framework WPF application on a Windows 10 system with attached Visual Studio 2019 Debugger.
I am calling this code from the constructor of my App
class.
public App()
{
this.InitializeAsync().ConfigureAwait(true);
}
Maybe it is not the the best way, but I am not sure if this is the reason for the weird behaviour.
The code starts with the UI thread and should do some Task.
With the await
operation and ConfigureAwait(true)
after the Task finishes it should continue on the Main Thread (1). But it does not.
Why?