Yura Zaletskyy Yura Zaletskyy - 4 months ago 11
C# Question

If async/await doesn't create new thread then explain this code

I've read this thread which claims with reference to msdn with idea that async/await doesn't create new threads. Please look at following code:

static class Program
{
static void Main(string[] args)
{
var task = SlowThreadAsync();
for(int i = 0; i < 5; i++)
{
Console.WriteLine(i * i);
}
Console.WriteLine("Slow thread result {0}", task.Result);
Console.WriteLine("Main finished on thread {0}", Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}

static async Task<int> SlowThreadAsync()
{
Console.WriteLine("SlowThreadAsync started on thread {0}", Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000);
Console.WriteLine("SlowThreadAsync completed on thread {0}", Thread.CurrentThread.ManagedThreadId);
return 3443;

}
}


As result of this code I got different ThreadId. Why the same thread gets different ThreadId?

different threads

Answer

You're using a console application for your example. This effects greatly the outcome of your test. A console application has no custom SynchronizationContext (like Winforms, WPF and ASP.NET have), hence it uses the ThreadPoolTaskScheduler to schedule continuations on an arbitrary thread-pool thread. Try this same example in a UI application and you'll see the continuation invoked on the same thread.