在WebApi或MVC控制器中使用ConfigureAwait(false)有任何危险吗?

说我有两个场景:

1)WebApi控制器

[System.Web.Http.HttpPost] [System.Web.Http.AllowAnonymous] [Route("api/registerMobile")] public async Task RegisterMobile(RegisterModel model) { var registerResponse = await AuthUtilities.RegisterUserAsync(model, _userService, User); if (registerResponse.Success) { var response = await _userService.GetAuthViewModelAsync(model.Username, User); return Request.CreateResponse(HttpStatusCode.OK, new ApiResponseDto() { Success = true, Data = response }); } else { return Request.CreateResponse(HttpStatusCode.OK, registerResponse); } } 

2)MVC控制器

  [Route("public")] public async Task Public() { if (User.Identity.IsAuthenticated) { var model = await _userService.GetAuthViewModelAsync(User.Identity.Name); return View("~/Views/Home/Index.cshtml", model); } else { var model = await _userService.GetAuthViewModelAsync(null); return View("~/Views/Home/Index.cshtml", model); } } 

我一直在阅读何时应该使用ConfigureAwait ,似乎我应该在所有不直接绑定到UI的异步调用上使用ConfigureAwait(false) 。 我不知道这意味着什么……我应该在所有上述await调用中使用.ConfigureAwait(false)吗?

我正在寻找一些关于何时应该使用它的明确指南。

这个问题与为所有服务器端代码调用ConfigureAwait的最佳实践不同 – 我正在寻找关于WebApi和MVC上下文中此方法的用例的简单答案,而不是一般的C#。

看起来我应该在所有不直接绑定到UI的异步调用上使用ConfigureAwait(false)。

不完全的。 这条指南在这里没有意义,因为没有UI线程。

传递给ConfigureAwait的参数是continueOnCapturedContext ,它更清楚地解释了该场景。 只要该async方法的其余部分依赖于当前上下文,您就希望使用ConfigureAwait(false)

在ASP.NET 4.x中,“context”是请求上下文,其中包括HttpContext.Current和culture等内容。 另外 – 这是未记录的部分 – 许多ASP.NET辅助方法确实依赖于请求上下文。

(旁注:ASP.NET Core不再具有“上下文”)

我应该在所有上述await调用中使用.ConfigureAwait(false)吗?

我没有听到任何关于此的确切指导,但我怀疑它没关系。

在我自己的代码中,我从不在我的控制器操作方法中使用ConfigureAwait(false) ,因此它们已经在请求上下文中完成。 这对我来说似乎更合适。

您可以在公共操作MVC Controller上使用ConfigureAwait ,如果_userService.GetAuthViewModelAsync保持等待,它有助于防止交易锁定。 如果异步服务保持等待,它会阻止UI的httpcontext。

看看下面的链接了解这种情况:

http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html