What is the point of having async Main?

杀马特。学长 韩版系。学妹 提交于 2019-12-18 04:39:23

问题


As we know, C#7 allows to make Main() function asynchronous.

What advantages it gives? For what purpose may you use async Main instead of a normal one?


回答1:


It's actually C# 7.1 that introduces async main.

The purpose of it is for situations where you Main method calls one or more async methods directly. Prior to C# 7.1, you had to introduce a degree of ceremony to that main method, such as having to invoke those async methods via SomeAsyncMethiod().GetAwaiter().GetResult().

By being able to mark Main as async simplifies that ceremony, eg:

static void Main(string[] args) => MainAsync(args).GetAwaiter().GetResult();

static async Task MainAsync(string[] args)
{
    await ...
}

becomes:

static async Task Main(string[] args)
{
    await ...
}

For a good write-up on using this feature, see C# 7 Series, Part 2: Async Main.



来源:https://stackoverflow.com/questions/46219114/what-is-the-point-of-having-async-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!