Ok, I guess I'm almost there on understanding all the fuzz on async / await
and multithreading. I understand that asynchronous is about tasks and multithreading is about workers. So you can have different tasks running on the same thread (this answer does a great job explaining it).
So I made a small programs in order to see the magic happening and I got a little confused:
public class Program
{
public static async Task Main(string[] args)
{
var task = ToastAsync();
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Cleaning the kitchen...");
await task;
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Take the toast");
}
public async static Task ToastAsync()
{
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Putting the toast");
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Setting a timer");
await Task.Delay(2000);
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Toast is ready");
}
}
Before running this program for the first time, I expected it to run on a single thread. Like the answer I linked above, I expected that this was the equivalent of "cleaning the kitchen while the toast's timer is running". The results though contradict it:
[1] Putting the toast
[1] Setting a timer
[1] Cleaning the kitchen...
[4] Toast is ready
[4] Take the toast
The above result doesn't make much sense to me. What is really happening? It seems part of the function is being executed in one thread and then, when it hits an await
point it handles the execution to another thread...? I didn't even know this was possible D:
Furthermore, I changed the above example a bit. In the main function, instead of await task;
I used task.Wait()
. And then the results changed:
[1] Putting the toast
[1] Setting a timer
[1] Cleaning the kitchen...
[4] Toast is ready
[1] Take the toast
Now this looks more like the example. It is like the timer on the toast worked as a different "cooker" though. But why is it different from using await
? And is there a way of getting asynchronous task fully in a single thread? I mean, by having Toast is ready
on thread 1
as well?
ThanksAsync!