gpt4 book ai didi

c# - 在 WebApi 或 MVC Controller 中使用 ConfigureAwait(false) 有什么危险吗?

转载 作者:IT王子 更新时间:2023-10-29 04:01:22 28 4
gpt4 key购买 nike

假设我有两种情况:

1) WebApi Controller

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

}

2) MVC Controller

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

我一直在研究什么时候应该使用 ConfigureAwait,似乎我应该在所有未绑定(bind)的异步调用上使用 ConfigureAwait(false)直接到用户界面。我不知道那是什么意思……我应该在上述所有 await 调用中使用 .ConfigureAwait(false) 吗?

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

此问题与 Best practice to call ConfigureAwait for all server-side code 不同- 我正在寻找关于此方法在 WebApi 和 MVC 上下文中的用例的直接答案,而不是一般的 C#。

最佳答案

it seems like I should use ConfigureAwait(false) on ALL of my async calls that are not tied directly to the UI.

不完全是。该准则在这里没有意义,因为没有 UI 线程。

传递给ConfigureAwait的参数是continueOnCapturedContext,更清楚的说明了场景。您想在 async 方法的其余部分依赖于当前上下文时使用 ConfigureAwait(false)

在 ASP.NET 4.x 中,“上下文”是请求上下文,包括 HttpContext.Current 和文化等内容。此外 - 这是未记录的部分 - 许多 ASP.NET 帮助器方法确实取决于请求上下文。

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

should I be using .ConfigureAwait(false) on all of the above await calls?

我还没有听到任何关于这方面的明确指导,但我怀疑这没问题。

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

关于c# - 在 WebApi 或 MVC Controller 中使用 ConfigureAwait(false) 有什么危险吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40198816/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com