ASP.NET MVC4 异步控制器 - 为什么要使用? [英] ASP.NET MVC4 Async controller - Why to use?

查看:31
本文介绍了ASP.NET MVC4 异步控制器 - 为什么要使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解为什么以及何时应该使用 async 控制器操作.最终,当我在其中使用 await 时,它将等待操作完成以返回视图.

例如

public async Task试试我(){等待 SomeActionAsync();返回视图();}

在这种情况下,如果我使用 async 或不使用 asyncAction 将花费相同的时间来执行.

如果我不尝试并行运行至少 2 个缓慢的操作(不相互依赖),我看不出有任何理由使用 async 控制器操作.>

如果我错了,请纠正我.我想我在这里遗漏了一些东西.

解决方案

await 关键字的目的是让您使用异步操作而无需编写丑陋的回调.

使用异步操作有助于避免浪费线程池线程.

说明

ASP.Net 在托管线程池中的线程中运行您的所有代码.
如果一次运行的慢请求太多,线程池会变满,新的请求需要等待线程释放.

但是,通常情况下,您的请求很慢并不是因为它们在进行计算(计算绑定),而是因为它们在等待其他东西,例如硬盘、数据库服务器或外部 Web 服务(IO- 或网络绑定).

仅仅为了等待外部操作完成而浪费宝贵的线程池线程是没有意义的.

异步操作允许您开始操作,将您的线程返回到池中,然后唤醒";操作完成时在不同的线程池线程上.
操作运行时,不消耗任何线程.

I am trying to understand why and when should I use an async controller action. Eventually, when I use await in it, it will wait for the operation to complete in order to return the View.

For example

public async Task<ActionResult> TryMe()
{
   await SomeActionAsync();
   return View();
}

In this case if I use the async or not using the async, the Action will take the same time to execute.

If I am not trying to run at least 2 slow operations (that are not dependent on each other) in parallel, I don't see any reason to use an async controller action.

Please correct me if I'm wrong. I think I'm missing something here.

解决方案

The point of the await keyword is to let you work with asynchronous operations without writing ugly callbacks.

Using asynchronous operations helps avoid wasting thread pool threads.

Explanation

ASP.Net runs all of your code in threads from the managed thread pool.
If you have too many slow requests running at once, the thread pool will get full, and new requests will need to wait for a thread to get free.

Frequently, however, your requests are slow not because they're doing computation (compute-bound), but because they're waiting for something else, such as a hard disk, a database server, or an external webservice (IO- or network-bound).

There is no point in wasting a precious threadpool thread simply to wait for the external operation to finish.

Asynchronous operations allow you to start the operation, return your thread to the pool, then "wake up" on a different thread pool thread when the operation is finished.
While the operation is running, no threads are consumed.

这篇关于ASP.NET MVC4 异步控制器 - 为什么要使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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