什么是好处是用与异步数据库调用等待 [英] 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数据库,它返回一个不完整的任务,当请求命中等待
,它返回请求的线程的线程池。以后,在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.
这篇关于什么是好处是用与异步数据库调用等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!