官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 绿春县| 库车县| 大邑县| 济宁市| 博湖县| 乌兰察布市| 宜都市| 修水县| 浙江省| 积石山| 潮安县| 通州市| 大庆市| 密云县| 普洱| 乳源| 英吉沙县| 长武县| 六枝特区| 成都市| 平顺县| 尼木县| 淄博市| 吉首市| 英德市| 交口县| 石阡县| 同江市| 平江县| SHOW| 南充市| 密山市| 樟树市| 绥阳县| 巴楚县| 宽甸| 双柏县| 毕节市| 邓州市| 永安市| 新乡市|