码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-11-03 19:03:40      阅读:263      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!