It is true that the async/await keywords do not create a new thread. However, a thread is needed to execute the remaining code which is exactly what happens in the code. Notice the thread Id is the same Id at the start of GetTaskOfTResultAsync(). It changes after the await.
static void Main(string[] args)
{
Test().GetAwaiter().GetResult();
}
static async Task Test()
{
Console.WriteLine("Test thread id " + Thread.CurrentThread.ManagedThreadId);
Task<int> returnedTaskTResult = GetTaskOfTResultAsync();
SynchronousTask();
int intResult = await returnedTaskTResult;
Console.WriteLine("Test thread Id " + Thread.CurrentThread.ManagedThreadId);
}
static async Task<int> GetTaskOfTResultAsync()
{
int hours = 10;
Console.WriteLine("GetTaskOfTResultAsync start thread id " + Thread.CurrentThread.ManagedThreadId);
await Task.Delay(2000);
Console.WriteLine("GetTaskOfTResultAsync end thread id " + Thread.CurrentThread.ManagedThreadId);
return hours;
}
static void SynchronousTask()
{
Console.WriteLine("SynchronousTask start thread id " + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("SynchronousTask end thread id " + Thread.CurrentThread.ManagedThreadId);
}
Results
Test thread id 1
GetTaskOfTResultAsync start thread id 1
SynchronousTask start thread id 1
SynchronousTask end thread id 1
GetTaskOfTResultAsync end thread id 4
Test thread Id 4