I understand the fundamentals of async/await however I see it mentioned a lot that await does not create a new thread. I can respect this since await could be using a hard disk I/O or network card or something besides a CPU where a new thread isn't desired.
What I'd like clarification on is whether, after the await is complete, the remainder of the async function is executed on a new thread? From what I can see in my own internal testing it does, as per the following code:
public static class Program
{
private static void Main(string[] args)
{
Thread.CurrentThread.Name = "ThisThread";
AnAsyncMethod();
while (true)
{
print("External While loop. Current Thread: " + Thread.CurrentThread.Name);
Thread.Sleep(200);
}
}
public static async void AnAsyncMethod()
{
for (int i = 0; i < 10; i++)
{
FakeWork();
print("doing fake pre-await work. Current Thread: " + Thread.CurrentThread.Name);
}
await Task.Run(FakeWork);
for (int i = 0; i < 10; i++)
{
FakeWork();
print("doing fake post-await work. Current Thread: " + Thread.CurrentThread.Name);
}
print("hello");
}
public static void FakeWork()
{
Thread.Sleep(100);
}
}
From this example it seems the same thread is used in the async method until it encounters its first await, at which time control is returned to the caller and the program continues. When the await completes, a new separate thread is started to continue onward within the async method instead of marshaling the earlier thread and forcing it to continue itself. This new thread executes concurrently with the earlier thread which is now being used elsewhere.
Is this correct?