What is the benefit to using await with an async d

2019-01-23 15:36发布

问题:

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 });
    }

What am I missing?

Does this provide some kind of performance benefit in the type of wait that will occur here?

回答1:

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.

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.

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.