Compartir a través de


How to call an async method from a console app main method

This article has been moved to its new home here:  https://benperk.github.io/msdn/2017/2017-03-how-to-call-an-async-method-from-a-console-app-main-method.html

I find myself needing to look this code snippet up time to time so I thought I’d write it up.

Check out some of my other articles I wrote in regards to ASP.NET Core and .Net Core

I needed to call an ASP.NET Core Web API which I discussed here, from a .NET Core Console Application, created similar to that shown in Figure 1.

image

Figure 1, how to create a .NET Core Console Application

Using the GetResponseAsync() method of the System.Net.WebResponce class, as you can see it needs to be call asynchronously.

 static private async Task callWebApi()
{
  WebResponse response = await WebRequest
      .Create("https://**?**.azurewebsites.net/api/sleepy")
      .GetResponseAsync()
      .ConfigureAwait(false);;
  WriteLine(response.StatusCode.ToString());
}

And in order to call and async method from the Main() method, I did the following.

 public static void Main(string[] args)
{
  try
  {
    callWebApi().Wait();
  }
  catch (Exception ex)
  {
    WriteLine($"There was an exception: {ex.ToString()}");
  }
}

You can also call the asynchronous method from the Main() method of the .NET Core console application using the Task.Run() method.

Task.Run(async () => { await callWebApi(); }).GetAwaiter().GetResult();  (it is not recommend to use the GetResult() method as it will block the thread)

Here are some nice articles written about Async Programming:

Comments

  • Anonymous
    December 21, 2018
    Thank you! This helped me.
  • Anonymous
    February 08, 2019
    This helped, thank you!