Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

c# 7.0 - What is the point of having async Main?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...