async、await在ASP.NET[ MVC]中之线程死锁的故事

场景重构

  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://*.com/questions/10004697/calling-configureawait-from-an-asp-net-mvc-action

上一篇:fiddler2请求参数乱码


下一篇:cookie 知识点