**dotnet core console** app: ConfigureAwait(true)

16 Views Asked by At

Below a dotnet core console app (I guess same if aspnet core/webapi apps).

class Program {
    static async Task Main(string[] args)
    {
        Console.WriteLine($"Simple Async #1. Thread ID: {Thread.CurrentThread.ManagedThreadId}"); # OK, thread Id = 1, the main thread.
        await Task.Delay(100).ConfigureAwait(true);
        Console.WriteLine($"Simple Async #2. Thread ID: {Thread.CurrentThread.ManagedThreadId}"); # Huh?  thread Id = 4?!? I thought ConfigureAwait(true) would instruct we'd return to original main thread after await?

    }
}

I am confused why at #2, Thread Id = 4. I expect Thread Id = 1 as ConfigureAwait(true) should give instruction we return to original context after await?

I am guessing, for dotnet core console and aspnet core/webapi's, synchronization context is not captured by default, so ConfigureAwait(true) doesn't actually have any effect on which thread the continuation runs on. It only takes effect in WPF, Winform..etc

For same argument, this would why with ConfigureAwait(false), we may see continuation tasks still running in new thread (not necessarily): it may still get executed in the same thread.

So essentially for dotnet core console and aspnet core/webapi's, ConfigureAwait does not guarantee whether it return or not return whether you set to True/False?

Am I mistaken?

0

There are 0 best solutions below