I've been learning asynchronous programming with async/await and how threading is involved. I've come to understand that it is a great way to achieve concurrency by not blocking the main thread with an IO task. And I've also read that IO tasks are not CPU bound and therefore don't require a thread. With that in mind, the following program confuses me:
static async Task Main()
{
//Retrieve Thread ID
Console.WriteLine($"Main Thread ID: {Thread.CurrentThread.ManagedThreadId}");
//Asynchronous work/IO task - get google.com
Task<string> goToGoogle = GetGoogle();
//Do work (CPU based)
Console.WriteLine("Doing calculations...");
Thread.Sleep(2000);
Console.WriteLine("Calculations complete");
//Store web page for later use
string page = await goToGoogle;
}
static async Task<string> GetGoogle()
{
var client = new HttpClient();
Console.WriteLine($"GetGoogle Thread ID before request: {Thread.CurrentThread.ManagedThreadId}");
var page = await client.GetStringAsync("http://google.com");
Console.WriteLine($"GetGoogle Thread ID after request: {Thread.CurrentThread.ManagedThreadId}");
return page;
}
//OUTPUT
//Main Thread ID: 1
//GetGoogle Thread ID before request: 1
//Doing calculations...
//GetGoogle Thread ID after request: 7
//Calculations complete
As demonstrated, the asynchronous method (GetGoogle) is run on another thread. From the placement of the Thread ID logs in GetGoogle, a new thread is used as soon as the request is made. It's not clear to me why another thread has been created to execute the supposedly IO bound task, which apparently shouldn't require a thread according to what I've read.
So, how come a new thread is used to perform this IO task? Would really appreciate some clarification on this concept!