Async Main
As we already know, in .NET Framework, the Main method is the main entry point from where the application/program is executed by the OS. For example, in ASP.NET Core, Program.cs is the main class where the Main method is defined, which creates a WebHost object, runs the Kestrel server, and loads up the HTTP pipeline as configured in the Startup class.
In the previous version of C#, the Main method had the following signatures:
public static void Main();
public static void Main(string[] args);
public static int Main();
public static int Main(string[] args);
In C# 7.0, we can use Async Main to perform asynchronous operations. The Async/Await feature was initially released in .NET Framework 4.5 in order to execute methods asynchronously. Today, many APIs provides Async/Await methods to perform asynchronous operations.
Here are some additional signatures of the Main method that have been added with C# 7.1:
public static Task Main();
public static Task Main(string[] args);
public static Task<int> Main();
public static Task<int> Main(string[] args);
Because of the preceding async signatures, we can now call async methods from the Main entry point itself and use await to perform an asynchronous operation. Here is a simple example of ASP.NET Core that calls the RunAsync method instead of Run:
public class Program
{
public static async Task Main(string[] args)
{
await BuildWebHost(args).RunAsync();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Async Main is a feature of C# 7.1, and to enable this feature in Visual Studio 2017, you can go to the project properties, click on the Advance button and set the Language version as C# latest minor version (latest), which is shown as follows: