I've seen a lot of post explaining that async/await in C# do not create a new thread like this one : tasks are still not threads and async is not parallel. I wanted to test it out myself so I wrote this code :
private static async Task Run(int id)
{
Console.WriteLine("Start:\t" + id + "\t" + System.Threading.Thread.CurrentThread.ManagedThreadId);
System.Threading.Thread.Sleep(500);
Console.WriteLine("Delay:\t" + id + "\t" + System.Threading.Thread.CurrentThread.ManagedThreadId);
await Task.Delay(100);
Console.WriteLine("Resume:\t" + id + "\t" + System.Threading.Thread.CurrentThread.ManagedThreadId);
System.Threading.Thread.Sleep(500);
Console.WriteLine("Exit:\t" + id + "\t" + System.Threading.Thread.CurrentThread.ManagedThreadId);
}
private static async Task Main(string[] args)
{
Console.WriteLine("Action\tid\tthread");
var task1 = Run(1);
var task2 = Run(2);
await Task.WhenAll(task1, task2);
}
Surprisingly I ended up with an output that looks like this :
Action id thread
Start: 1 1
Delay: 1 1
Start: 2 1
Resume: 1 4 < ------ problem here
Delay: 2 1
Exit: 1 4
Resume: 2 5
Exit: 2 5
From what I see, it is indeed creating new threads, and even allowing two piece of code to run concurrently? I need to use async/await in a non thread-safe environment so I can't let it create new threads. Why is it that the task "1" is allowed to resume ( after the Task.Delay
) while task "2" is currently running ?
I tried adding ConfigureAwait(true)
to all the await
but it doesn't change anything.
Thanks!