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

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

问题描述

我有这个简单的code:

I have this simple code :

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

大。这个编译。

但可以说我有一个控制台应用程序,我想运行code以上(调用 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();
        }

但我读过(当使用同步)我有一路同步的最高

:那么,这是否意味着我的函数应该标记为异步

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:

切入点不能打上异步修改

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

如果我理解异步的东西,该线程将进入功能----> 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

我是什么失踪?

推荐答案

在大多数的项目类型,你的异步向上和向下将在结束异步无效事件处理函数或返回工作你的框架。

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.

您可以只做了等待对返回的任务:

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

异步更多信息控制台应用程序是的在我的博客

More information for async Console apps is on my blog.

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

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