Switching to a different thread with async/await in C#

The code below switches to a different thread when the execution of Main() is resumed at line 11:

internal class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            HttpClient client = new HttpClient();

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");
                
            HttpResponseMessage response = await client.GetAsync("https://developernote.com/");

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");

            response.EnsureSuccessStatusCode();

            string responseBody = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");

            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");

            Console.WriteLine($"Message: {e.Message}");
        }
    }
}

The output is:

Thread: 1
Thread: 7
Thread: 7
<!DOCTYPE html>
<html lang="en-US">
<head>
...

The exception is also caught on a separate thread.

Leave a Reply

Your email address will not be published. Required fields are marked *