问题
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