SB2*_*055 43 .net c# asp.net-mvc asynchronous asp.net-web-api
说我有两个场景:
1)WebApi控制器
[System.Web.Http.HttpPost]
[System.Web.Http.AllowAnonymous]
[Route("api/registerMobile")]
public async Task<HttpResponseMessage> 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);
}
}
Run Code Online (Sandbox Code Playgroud)
2)MVC控制器
[Route("public")]
public async Task<ActionResult> 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我一直在阅读我应该使用的时间ConfigureAwait,似乎我应该使用ConfigureAwait(false)所有不直接与UI绑定的异步调用.我不知道那意味着什么......我应该.ConfigureAwait(false)在上述所有await电话中使用吗?
我正在寻找一些关于何时应该使用它的明确指南.
这个问题与为所有服务器端代码调用ConfigureAwait的最佳实践不同 - 我正在寻找关于WebApi和MVC上下文中此方法的用例的简单答案,而不是一般的C#.
Ste*_*ary 61
看起来我应该在所有不直接绑定到UI的异步调用上使用ConfigureAwait(false).
不完全的.这条指南在这里没有意义,因为没有UI线程.
传递给的参数ConfigureAwait是continueOnCapturedContext,更清楚地解释了场景.ConfigureAwait(false)只要该async方法的其余部分不依赖于当前上下文,您就希望使用它.
在ASP.NET 4.x中,"上下文"是请求上下文,其中包括类似于HttpContext.Current文化的内容.另外 - 这是未记录的部分 - 许多ASP.NET辅助方法确实依赖于请求上下文.
(旁注:ASP.NET Core不再具有"上下文")
我应该在所有上述await调用中使用.ConfigureAwait(false)吗?
我没有听到任何关于此的确切指导,但我怀疑它没关系.
在我自己的代码中,我从不ConfigureAwait(false)在我的控制器操作方法中使用,因此它们已经在请求上下文中完成.这对我来说似乎更合适.
| 归档时间: |
|
| 查看次数: |
10930 次 |
| 最近记录: |