async、await在ASP.NET[ MVC]中之線程死鎖的故事
阿新 • • 發佈:2017-11-03
div pos ask 其他 flow ron ttpClient com async
場景重構
public ActionResult Index(string ucode) { string userInfo = GetUserInfo(ucode).Result; ViewData["UserInfo"] = userInfo; return View(); } // 這樣調用死鎖 async Task<string> GetUserInfo(string ucode) { HttpClient client = new HttpClient(); var httpContent = new FormUrlEncodedContent(new Dictionary<string, string>() { {"ucode", ucode} }); string uri = "http://www.xxxx.com/user/get"; var response = await client.PostAsync(uri, httpContent); return response.Content.ReadAsStringAsync().Result; }
解決方案
// 其他網友的解決方案 // 也是有問題的 async Task<string> GetUserInfo1(string ucode) { HttpClient client = new HttpClient(); var httpContent = new FormUrlEncodedContent(new Dictionary<string, string>() { {"ucode", ucode} }); string uri = "http://www.xxxx.com/user/get"; var response = client.PostAsync(uri, httpContent).Result.Content.ReadAsStringAsync().Result; return response; } // 最終解決方案 string GetUserInfo2(string ucode) { HttpClient client= new HttpClient(); var httpContent = new FormUrlEncodedContent(new Dictionary<string, string>() { {"ucode", ucode} }); string uri = "http://www.xxxx.com/user/get"; var response = client.PostAsync(uri, httpContent).ConfigureAwait(false).GetAwaiter().GetResult().Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult(); return response; }
參考 網址: https://stackoverflow.com/questions/10004697/calling-configureawait-from-an-asp-net-mvc-action
async、await在ASP.NET[ MVC]中之線程死鎖的故事