我有这个简单的代码:
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# 中的控制台应用程序?
发布评论