Website Links

Thursday, 18 May 2017

C# - Asynchronicity and the Main Thread

When you call an asynchronous method from your Main method of a console application in C#, you may experience the situation where your program runs to completion without hitting breakpoints following an await. An example of this is below:


  namespace ConsoleTests
  {
      class Program
      {
          static void Main(string[] args)
          {
              var content = Get(args[0]);
          }

          public static async Task Get(string url)
          {
              using (HttpClient client = new HttpClient()) {
                  HttpResponseMessage response = await client.GetAsync(url);

                  //Breakpoint set here
              }
          }
      }
  }


The reason for this is that when Main exits the program exists, and any outstanding async operations are cancelled along with it. This can be solved by changing
 var content = Get(args[0]); 
to
 var content = Get(args[0]).Wait(); 
to block Main from exiting.

No comments:

Post a Comment