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

编程入门 行业动态 更新时间:2024-10-28 04:23:46
本文介绍了异步在 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# 中的控制台应用程序?

本文发布于:2023-11-10 06:49:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   应用程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!