僵局:一個實踐的例子
c#'s async
/await
簡化異步編程,改善代碼可讀性。 但是,忽視同步環境可能會導致死鎖。本文研究了一個常見的僵局場景並提供解決方案。
了解僵局問題
在異步編程中,常見的陷阱涉及單線讀取的非倫敦同步上下文中的死鎖,例如Windows UI線程或ASP.NET請求上下文。考慮此代碼:
<code class="language-csharp">public ActionResult ActionAsync() { // DEADLOCK: Blocking on the async task var data = GetDataAsync().Result; return View(data); } private async Task<string> GetDataAsync() { // Simple async method var result = await MyWebService.GetDataAsync(); return result.ToString(); }</code>僵局分析
主線程啟動
,並使用立即阻止,等待完成。 GetDataAsync()
>的背景任務嘗試執行。 由於同步上下文是單線讀取的,因此主線程保持上下文,阻止了背景任務繼續。
.Result
>的延續被阻止,直到上下文線程釋放(通過主線程),而主線程停滯不前,等待GetDataAsync()
GetDataAsync()
解決方案:防止僵局GetDataAsync()
遵循以下準則以防止死鎖:
>策略性異步/等待使用:
async
await
>以上是在C#中使用異步/等待時,如何避免僵局?的詳細內容。更多資訊請關注PHP中文網其他相關文章!