[英]Is there any danger in using ConfigureAwait(false) in WebApi or MVC controllers?
假設我有兩種情況:
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);
}
}
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);
}
}
我一直在閱讀何時應該使用ConfigureAwait
似乎我應該在所有未直接綁定到 UI 的異步調用上使用ConfigureAwait(false)
。 我不知道這意味着什么......我應該在上述所有await
調用中使用.ConfigureAwait(false)
嗎?
我正在尋找一些明確的指導方針,以確定我應該何時使用它。
這個問題與為所有服務器端代碼調用 ConfigureAwait的最佳實踐不同- 我正在尋找關於 WebApi 和 MVC 上下文中此方法的用例的直接答案,而不是一般的 C#。
似乎我應該在所有未直接綁定到 UI 的異步調用上使用 ConfigureAwait(false)。
不完全是。 該指南在這里沒有意義,因為沒有 UI 線程。
傳遞給ConfigureAwait
的參數是continueOnCapturedContext
,它更清楚地解釋了場景。 只要該async
方法的其余部分不依賴於當前上下文,您就希望使用ConfigureAwait(false)
。
在 ASP.NET 4.x 中,“上下文”是請求上下文,其中包括HttpContext.Current
和文化等內容。 此外 - 這是未記錄的部分 - 許多 ASP.NET 幫助程序方法確實依賴於請求上下文。
(旁注:ASP.NET Core 不再有“上下文”)
我應該在上述所有等待調用中使用 .ConfigureAwait(false) 嗎?
我還沒有聽到任何關於這方面的明確指導,但我懷疑這沒問題。
在我自己的代碼中,我從不在我的控制器操作方法中使用ConfigureAwait(false)
,因此它們已經在請求上下文中完成。 對我來說似乎更合適。
如果 ASP.NET Core 應用程序中沒有實際上下文,那么將 .ConfigureAwait(false) 添加到控制器的可等待方法中應該沒有壞處也沒有好處。
但是,如果將來有機會,無論出於何種原因,需要考慮諸如 ASP.NET 4 中的上下文之類的東西,那將是另一回事。 我們不能冒險在不同的上下文中運行,除非我們不在乎它(在這種情況下,我們可以使用任何可用於處理的線程,從而可能提高性能)。
我的選擇是添加 ConfigureAwait(false) 即使它沒有被使用。
您可以在公共操作MVC Controller上使用ConfigureAwait ,如果您的_userService.GetAuthViewModelAsync一直在等待,它有助於防止交易鎖定。 如果異步服務保持等待,則雲會引發死鎖,因此可能會阻止 UI 的 httpcontext。
請查看以下鏈接以了解此案例:
http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
在控制器中使用ConfigureAwait(false)
對我來說聽起來不太好,因為它會使主線程等待操作完成。 我想出的最好方法是在您的服務/業務層和持久層中使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.