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


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("http://**?**.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();

Here are some nice articles written about Async Programming:

Comments (0)

Skip to main content