I think I've read around 20 async/await articles, multiple questions on SO and I still have lots of gaps in understanding how it works, especially when multiple threads are involved and when its all done using one thread.
I wrote myself this piece of code to test one scenario:
static async Task Main(string[] args)
{
var longTask = DoSomethingLong();
for (int i = 0; i < 1000; i++)
Console.Write(".");
await longTask;
}
static async Task DoSomethingLong()
{
await Task.Delay(10);
for (int i = 0; i < 1000; i++)
Console.Write("<");
}
I'm explicitly letting my Main continue with writing the dots to the console while the execution is blocked on delay inside DoSomethingLong. I see that after delay ends, the dots writing and < sign writing start interfering with each other.
I just can't figure out: is it two threads that are doing this work simultaneously? One writes the dots and the other writes the other characters? Or is it somehow one thread but switching between those contexts? I would say it's the first option but still I am not sure. When can I expect an additional thread to be created when using async/await? This is still not clear to me.
Also is it always the same thread that will execute Mai, reach the await and then come back to write the dots?