异步在 C# 中的控制台应用程序? [英] async at console app in C#?

查看:19
本文介绍了异步在 C# 中的控制台应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的代码:

public static async Task<int> SumTwoOperationsAsync()
{
    var firstTask = GetOperationOneAsync();
    var secondTask = GetOperationTwoAsync();
    return await firstTask + await secondTask;
}


private async Task<int> GetOperationOneAsync()
{
    await Task.Delay(500); // Just to simulate an operation taking time
    return 10;
}

private async Task<int> GetOperationTwoAsync()
{
    await Task.Delay(100); // Just to simulate an operation taking time
    return 5;
}

太好了.这编译.

但是假设我有一个控制台应用程序,我想运行上面的代码(调用 SumTwoOperationsAsync())

But Lets say I have a console app and I want to run the code above ( calling SumTwoOperationsAsync())

 static  void Main(string[] args)
        {
             SumTwoOperationsAsync();
        }

但我读过(使用 sync 时)我必须一直同步向上向下:

But I've read that (when using sync) I have to sync all the way up and down :

问题:这是否意味着我的 Main 函数应该被标记为 async ?

Question : So does this means that my Main function should be marked as async ?

好吧,不可能是因为存在编译错误:

Well it can't be because there is a compilation error:

入口点不能用 'async' 修饰符标记

an entry point cannot be marked with the 'async' modifier

如果我理解异步的东西,线程将进入Main函数----> SumTwoOperationsAsync ---->将调用两个函数和会出来.但直到 SumTwoOperationsAsync

If I understand the async stuff , the thread will enter the Main function ----> SumTwoOperationsAsync ---->will call both functions and will be out. but until the SumTwoOperationsAsync

我错过了什么?

推荐答案

在大多数项目类型中,您的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.

这篇关于异步在 C# 中的控制台应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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