有什么区别:

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

和:
[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);
}

我看到 MVC 代码现在有 async 但有什么区别。一个比另一个提供更好的性能吗?用一个比另一个更容易调试问题吗?我应该为我的应用程序更改其他 Controller 以添加 Async 吗?

最佳答案

异步操作仅在您执行 I/O 绑定(bind)操作(例如远程服务器调用)时才有用。异步调用的好处是在 I/O 操作期间,没有使用 ASP.NET 工作线程。下面是第一个示例的工作原理:

  • 当请求命中操作时,ASP.NET 从线程池中取出一个线程并开始执行它。
  • IdentityManager.Authentication.CheckPasswordAndSignIn 方法被调用。这是一个阻塞调用 -> 在整个调用过程中,工作线程受到威胁。

  • 这是第二个调用的工作原理:
  • 当请求命中操作时,ASP.NET 从线程池中取出一个线程并开始执行它。
  • 调用 IdentityManager.Authentication.CheckPasswordAndSignInAsync 立即返回。注册 I/O 完成端口,并将 ASP.NET 工作线程释放到线程池。
  • 稍后当操作完成时,I/O Completion 端口发出信号,从线程池中抽取另一个线程完成返回 View 。

  • 正如您在第二种情况下看到的,ASP.NET 工作线程只使用了很短的时间。这意味着池中有更多线程可用于服务其他请求。

    所以总而言之,只有当你有一个真正的异步 API 时才使用异步操作。如果您在异步操作中进行阻塞调用,您将失去它的全部好处。

    关于asp.net-mvc - 在 MVC5 中使用异步有什么好处?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19087513/

    10-14 16:34
    查看更多