18

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?

Exerion
  • 449
  • 7
  • 20
  • 4
    async does not compose very well, if you want to await something properly then you have to make your method async as well. Turtles all the way up, bummer if that is the Main() method. – Hans Passant Sep 14 '17 at 12:51

1 Answers1

26

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.

Tomas Voracek
  • 5,886
  • 1
  • 25
  • 41
David Arno
  • 42,717
  • 16
  • 86
  • 131
  • 1
    it seems they changed their mind multiple times. https://stackoverflow.com/a/9212343/4767498 it was allowed, then disallowed, then allowed again hmm. would be interesting to know the reason behind it. – M.kazem Akhgary Sep 16 '17 at 19:45
  • 1
    @David - What I can't understand is, given that control yields to the caller upon on await, why despite the async main that the console app doesn't just exit before any execution can finish...? – Howiecamp Aug 25 '18 at 23:18
  • 7
    The internal implementation of the "async main" is just a synchronous wrapper that does .Wait(). – Austin Salgat Aug 31 '18 at 04:34
  • 1
    @Salgat good point! I looked at the IL produced by a .NET Core 2.2 console app using latest C# language features and it did have a void Main method in there calling GetAwiater().GetResult() on the async Main. But I still appreciate not having to write that myself :-) – Sudhanshu Mishra Apr 29 '19 at 02:20