使用Await顺序调用异步任务的优势是什么?

Mik*_*kee 1 .net c# asynchronous task-parallel-library async-await

在仔细阅读Visual Studio 2013创建的AccountController代码时.我看到了对每个调用执行await的异步方法的顺序调用模式.

public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl){
  if (User.Identity.IsAuthenticated){
    return RedirectToAction("Manage");
  }

  if (ModelState.IsValid){
    // Get the information about the user from the external login provider
    var info = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (info == null){
      return View("ExternalLoginFailure");
   }

   var user = new ApplicationUser() { UserName = model.UserName };
   var result = await UserManager.CreateAsync(user);
   if (result.Succeeded){
     result = await UserManager.AddLoginAsync(user.Id, info.Login);
     if (result.Succeeded){
       await SignInAsync(user, isPersistent: false);
       return RedirectToLocal(returnUrl);
      }
   }
   AddErrors(result);
 }

 ViewBag.ReturnUrl = returnUrl;
 return View(model);
}
Run Code Online (Sandbox Code Playgroud)

我没有看到这种等待 - 异步模式有什么优势吗? await运算符进行这些阻塞调用,这使得它们基本上是老式的同步调用.

回答

由于缺乏声誉,我还不能回答我自己的问题,但我在这里找到答案,而在发布前我做了搜索,我错过了.调用是阻塞的,我错过了,并且在文档中一点也不清楚,ASP.NET是否在阻塞期间将当前工作线程返回到ASP.NET线程池.

进一步阅读 TAP(基于任务的异步模式)是.NET Framework中的新模式异步.这里有关于模式的更多信息的链接,而不是大多数人想要消化的信息.

i3a*_*non 6

调用async方法不会阻止任何事情.但是,代码看起来像是同步的.一个async方法返回表示异步操作的任务.操作结束时,任务结束.

是什么await做的是后它基本上注册所有代码的延续.它将在操作结束时运行.它没有被阻止,它将在需要运行时被调用.那里有很大的不同.

例如,当我调用Web服务并打印结果时.当然我不能打印我没有的东西,但是我没有调用服务并等待结果,而是调用服务并告诉它如何处理结果(打印).