标签:cli new enc har 重构 blog inf sharp class
场景重构
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]中之线程死锁的故事
标签:cli new enc har 重构 blog inf sharp class
原文地址:http://www.cnblogs.com/liuxiaoji/p/7779101.html