使用与MVC5异步的优势是什么?

116 asp.net-mvc task-parallel-library async-await asp.net-mvc-5 asp.net-identity

有什么区别:

public ActionResult Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        IdentityResult result = IdentityManager.Authentication.CheckPasswordAndSignIn(AuthenticationManager, model.UserName, model.Password, model.RememberMe);
        if (result.Success)
        {
            return Redirect("~/home");
        }
        else
        {
            AddErrors(result);
        }
    }
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

和:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        IdentityResult result = await IdentityManager.Authentication.CheckPasswordAndSignInAsync(AuthenticationManager, model.UserName, model.Password, model.RememberMe);
        if (result.Success)
        {
            return Redirect("~/home");
        }
        else
        {
            AddErrors(result);
        }
    }
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

我看到MVC代码现在有异步,但有什么区别.一个人的表现比另一个人好得多吗?调试一个问题比另一个问题更容易吗?我是否应该为我的应用程序更改其他控制器以添加异步?

Dar*_*rov 165

只有在执行远程服务器调用等I/O绑定操作时,异步操作才有用.异步调用的好处是在I/O操作期间,没有使用ASP.NET工作线程.所以这是第一个例子的工作原理:

  1. 当请求到达操作时,ASP.NET从线程池中获取一个线程并开始执行它.
  2. IdentityManager.Authentication.CheckPasswordAndSignIn调用该方法.这是一个阻塞调用 - >在整个调用期间,工作线程正在受到危害.

以下是第二次调用的工作原理:

  1. 当请求到达操作时,ASP.NET从线程池中获取一个线程并开始执行它.
  2. IdentityManager.Authentication.CheckPasswordAndSignInAsync被称为其立即返回.注册I/O完成端口,并将ASP.NET工作线程释放到线程池.
  3. 稍后当操作完成时,将发出I/O完成端口信号,从线程池中抽取另一个线程以完成返回视图.

正如您在第二种情况中所看到的,ASP.NET工作线程仅在短时间内使用.这意味着池中有更多线程可用于提供其他请求.

总而言之,只有在内部具有真正的异步API时才使用异步操作.如果您在异步操作中进行阻止调用,则会终止它的全部好处.