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

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:

主站蜘蛛池模板: 永德县| 德格县| 盐津县| 红原县| 奉化市| 大埔区| 通山县| 奇台县| 隆德县| 永川市| 沛县| 乌拉特后旗| 望奎县| 乌拉特前旗| 工布江达县| 鄢陵县| 江孜县| 来凤县| 广东省| 宁河县| 长顺县| 如皋市| 加查县| 砀山县| 托克逊县| 观塘区| 涿鹿县| 临颍县| 黑水县| 仁怀市| 瑞安市| 社旗县| 平果县| 酒泉市| 仙桃市| 简阳市| 甘德县| 海伦市| 阳信县| 双桥区| 申扎县|