将 await 与异步数据库调用一起使用有什么好处 [英] What is the benefit to using await with an async database call
问题描述
我只是在查看默认的 MVC5 项目以及它如何在控制器中使用异步.
I am just looking at the default MVC5 project and how it uses async in the controllers.
我想知道异步在这里比简单地使用同步调用有什么好处:
I would like to know what benefit async provides here over simply using synchronous calls:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
{
ManageMessageId? message = null;
//why use an async database call here with await instead of just using a synchronous one?
IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("Manage", new { Message = message });
}
我错过了什么?
这是否会在此处发生的等待类型中提供某种性能优势?
Does this provide some kind of performance benefit in the type of wait that will occur here?
推荐答案
在服务器端(例如,ASP.NET MVC),您所做的任何 I/O(例如,数据库)都应该异步完成.这会在 I/O 进行中释放请求线程.
On the server side (e.g., ASP.NET MVC), any I/O you do (e.g., databases) should be done asynchronously. This frees up the request thread for the time that the I/O is in flight.
所以,当RemoveLoginAsync
向数据库发送它的SQL时,它返回一个未完成的任务,当请求命中await
时,它返回请求线程给线程池.之后,当DB操作完成时,从线程池中取出一个请求线程,用于继续请求.
So, when the RemoveLoginAsync
sends its SQL to the database, it returns an incomplete task, and when the request hits the await
, it returns the request thread to the thread pool. Later, when the DB operation completes, a request thread is taken from the thread pool and used to continue the request.
最终结果是可扩展性,因为(至少在 99.9% 的情况下)任务比线程可扩展性更好.但是,如果您的数据库只是一个服务器并且所有请求都访问数据库,那么这并没有太大的优势,因为在这种情况下,您的可扩展性瓶颈是数据库服务器,而不是 Web 服务器.
The end result is scalability, because (in the 99.9% case at least) tasks scale better than threads. However, there isn't a big advantage if your database is just a single server and all requests hit the db, because your scalability bottleneck in that scenario is the db server, not the web server.
这篇关于将 await 与异步数据库调用一起使用有什么好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!