异步一路下滑问题

编程入门 行业动态 更新时间:2024-10-07 09:29:06
本文介绍了异步一路下滑问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个异步asp控制器。该控制器调用异步方法。实际执行异步IO工作的方法,是内心深处在我的应用程序。该系列的控制器和在链中的最后一个方法之间的方​​法都标有异步改性剂。下面是我怎么有code设置一个例子:

I have an async asp controller. This controller calls an async method. The method that actually performs the async IO work is deep down in my application. The series of methods between the controller and the last method in the chain are all marked with the async modifier. Here is an example of how I have the code setup:

public async Task<ActionResult> Index(int[] ids) { List<int> listOfDataPoints = dataPointService(ids); List<Task> dpTaskList = new List<Task>(); foreach (var x in listOfDataPoints) { dpTaskList.Add(C_Async(x)); } await Task.WhenAll(dpTaskList); return View(); } private async Task C_Async(int id) { //this method executes very fast var idTemp = paddID(id); await D_Async(idTemp); } private async Task D_Async(string id) { //this method executes very fast await E_Async(id); } private async Task E_Async(string url) { //this method performs the actual async IO result = await new WebClient().DownloadStringTaskAsync(new Uri(url)) saveContent(result); }

正如你所看到的控制器调用C_Async(x)的异步再有是一串串的异步方法E_Async。有控制器和E_Async的方式,所有具有异步修饰符。是否有性能损失,因为不存在使用异步modifyer方法,但没有做任何异步IO工作?

As you can see the controller calls C_Async(x) asynchronously then there is a chain of async methods to E_Async. There are methods between the controller and E_Async and all have the async modifier. Is there a performance penalty since there are methods using the async modifyer but not doing any async IO work?

注意:这是真正的code的简化版本有控制器和E_Async方法之间有更多异步方法

Note: This is a simplified version of the real code there are more async methods between the controller and the E_Async method.

推荐答案

是的。有一个点球(虽然不是一个巨大的),如果你不这样做的需要是异步不要。这种模式通常被称为回等待在这里你可以几乎总是同时删除异步和计谋。简单地回到你已经有一个重新presents的异步操作任务:

Yes. There is a penalty (though not a huge one), and if you don't need to be async don't be. This pattern is often called "return await" where you can almost always remove both the async and the await. Simply return the task you already have that represents the asynchronous operations:

private Task C_Async(int id) { // This method executes very fast var idTemp = paddID(id); return D_Async(idTemp); } private Task D_Async(string id) { // This method executes very fast return E_Async(id); }

在这种特殊情况下首页只会等待的的任务E_Async 的回报。这意味着,以后所有的 I / O 做的code中的下一行,将直接返回查看(); 。 C_Async 和 D_Async 已经运行,并在同步调用完成。

In this specific case Index will only await the tasks that E_Async returns. That means that after all the I/O is done the next line of code will directly be return View();. C_Async and D_Async already ran and finished in the synchronous call.

更多推荐

异步一路下滑问题

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

发布评论

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

>www.elefans.com

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