且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

异步在 C# 中的控制台应用程序?

更新时间:2023-02-13 08:18:18

在大多数项目类型中,您的async向上"和向下"将以async void结束> 事件处理程序或将 Task 返回到您的框架.

In most project types, your async "up" and "down" will end at an async void event handler or returning a Task to your framework.

但是,控制台应用程序不支持此功能.

However, Console apps do not support this.

您可以只对返回的任务执行Wait:

You can either just do a Wait on the returned task:

static void Main()
{
  MainAsync().Wait();
  // or, if you want to avoid exceptions being wrapped into AggregateException:
  //  MainAsync().GetAwaiter().GetResult();
}

static async Task MainAsync()
{
  ...
}

或者你可以使用你自己的上下文,就像我写的那样:

static void Main()
{
  AsyncContext.Run(() => MainAsync());
}

static async Task MainAsync()
{
  ...
}

async 控制台应用程序的更多信息是 在我的博客上.

More information for async Console apps is on my blog.