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

This article has been moved to its new home here:

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.


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

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

 public static void Main(string[] args)
  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: