拥有Main Main有什么意义? [英] What is the point of having async Main?

查看:85
本文介绍了拥有Main Main有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,C#7允许使Main()函数异步.

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

它具有什么优势?出于什么目的,您可以使用异步Main代替普通的Main?

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

推荐答案

实际上是引入异步main的C#7.1.

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

它的目的是在您Main方法直接调用一个或多个异步方法的情况下.在C#7.1之前,您必须为该主要方法引入某种程度的仪式,例如必须通过SomeAsyncMethod().GetAwaiter().GetResult()调用那些异步方法.

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

通过将Main标记为async可以简化该仪式,例如:

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 ...
}

成为:

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

有关使用此功能的文章,请参见

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

这篇关于拥有Main Main有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆