0

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!

Calculon
  • 61
  • 6
  • 5
    It shows that GetGoogle() does not start on another thread, id 1 is the main thread. GetStringAsync() does not run on any thread, that's what you read about. The continuation after it does indeed run on a threadpool thread, necessarily so because a console mode app does not have a way to run it on the original thread. https://stackoverflow.com/a/52687947/17034 – Hans Passant Jan 03 '22 at 11:51
  • 5
    The *continuation* is run on another thread. But the IO operation itself does not use any threads at all. [**There Is No Thread**](https://blog.stephencleary.com/2013/11/there-is-no-thread.html) – Charlieface Jan 03 '22 at 12:02
  • Got it, thanks for the clarification + resources! – Calculon Jan 03 '22 at 12:23

0 Answers0