What is the point of having async Main?

前端 未结 1 1496
旧巷少年郎
旧巷少年郎 2020-12-10 12:19

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条回答
  • 2020-12-10 12:37

    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 SomeAsyncMethod().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.

    0 讨论(0)
提交回复
热议问题