使用异步 Main 有什么意义? [英] What is the point of having async Main?

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

问题描述

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

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

它有什么优势?您可以出于什么目的使用 async Main 而不是普通的 Main?

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

推荐答案

实际上是 C# 7.1 引入了 async main.

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

有关使用此功能的详细介绍,请参阅 C# 7 系列,第 2 部分:异步主.

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

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

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