简体   繁体   English

MVC 4 Web Api:从操作返回任务

[英]MVC 4 Web Api: returning tasks from actions

Probably there is some mess in my head, but I see a kind of confusion in the following: 我的脑海中可能有些混乱,但我在以下方面感到困惑:

  • Web API controllers are derived from the ApiController class, where the main method is ExecuteAsync, which make the request go through the pipe of filters and action, returning Task at the end; Web API控制器派生自ApiController类,其中的主要方法是ExecuteAsync,该类使请求通过过滤器和操作的管道,最后返回Task;
  • Web API actions support ability to return object of type Task, utilizing TPL or async/await. Web API操作支持利用TPL或异步/等待返回任务类型的对象的能力。

My question is: do I really benefit from constructing and runing tasks within API actions? 我的问题是:我真的可以从API动作中构造和运行任务中受益吗? As far as I understand, the goal to return threads back into ASP.NET threadpool ASAP is already carried out by ApiController.ExecuteAsync infrastructure, therefore additional level of async gives me nothing (except if I need cancellation for task or performing operations in backend in parallel). 据我了解,ApiController.ExecuteAsync基础结构已经实现了将线程尽快返回ASP.NET线程池的目标,因此额外的异步级别没有任何作用(除非我需要取消任务或在后端执行操作)平行)。

Any thoughts? 有什么想法吗? Thanks. 谢谢。

As with any parallel programming the answer is unfortunately: it completely depends on the kind of processing you're doing. 与任何并行编程一样,不幸的是答案是:它完全取决于您正在执行的处理类型。

For starters, the ASP.NET runtime is already providing concurrency per request. 对于初学者来说,ASP.NET运行时已经为每个请求提供并发性。 Therefore if the work you're doing is entirely compute bound then there is very little benefit to using async. 因此,如果您正在做的工作完全是受计算限制的,那么使用异步几乎没有什么好处。 The exception to that rule is if the data your processing in the request is very large and, thus, would benefit from further concurrency. 该规则的例外是,如果您在请求中处理的数据非常大,因此可以从进一步的并发中受益。

The most important scenarios where it does make sense to use async is when you're doing any kind of I/O work (disk I/O or network I/O). 如果它确实是有意义的使用异步最重要的场景是当你在做任何类型的I / O工作(磁盘I / O 网络I / O)。 For example when your ASP.NET controller code... 例如,当您的ASP.NET控制器代码...

  • communicates with another backend web service 与另一个后端Web服务通信
  • communicates with the database server 与数据库服务器通信
  • reads/writes file information to the disk 读取/写入文件信息到磁盘

You want to use async in these cases because there is wait time while the I/O requests are fulfilled: either disk or network latency. 在这些情况下,您需要使用异步,因为在满足I / O请求的过程中会有等待时间:磁盘或网络延迟。 By using async you free the CPU thread that would have otherwise been blocked waiting on that data so that it can process some other compute bound work. 通过使用异步,您可以释放原本会在等待该数据的情况下阻塞的CPU线程,以便它可以处理其他一些受计算限制的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM