【问题标题】:HttpClient call in asp.netasp.net 中的 HttpClient 调用
【发布时间】:2013-03-08 18:06:41
【问题描述】:

我在调用 HttpClient 类和异步调用时遇到问题。我从 page_load 调用函数 List()。调用从 HttpResponseMessage response = await client.GetAsync(str); 行返回并且永远不会回来完成它。

我不明白我在做什么错误。以下是我的代码:

        protected void Page_Load(object sender, EventArgs e)
        {
            Task<string> s= List(product); 
        }

        protected async Task<string> List(string ProductType)
        {
            string str = "http://xx.xx.com/wiki/api.php";


            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", "username", "password"))));
                HttpResponseMessage response = await client.GetAsync(str);

                response.EnsureSuccessStatusCode();

                string content = await response.Content.ReadAsStringAsync();
            }
            return content;
         }

它从不执行以下行。

response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();

请帮忙。提前致谢。

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    你永远不会在Page_Load 中显示任务发生了什么,但鉴于你的症状以及Page_Load 不是async 的事实,我敢打赌你打电话给ResultWaitawaiting。

    当你这样做时,你cause a deadlock。我的博客链接详细解释了这一点,但要点是await 将捕获并恢复当前的“上下文”。在 ASP.NET 中,这是一个请求上下文,请求上下文一次只允许一个线程在其中执行。因此,如果您调用ResultWait(在请求上下文中),您将阻塞该请求上下文中的线程,直到Task&lt;string&gt; 完成。同时,当HttpClient 得到响应时,它会尝试在await client.GetAsync(str) 之后恢复。但是请求上下文一次只允许一个线程进入,并且该线程被阻塞等待Task 完成。由于上下文繁忙,List 无法完成,因此您遇到了死锁。

    为了防止死锁,请关注这两个best practices (from my recent MSDN article)

    1. 一直使用async。也就是说,使用await 而不是ResultWait
    2. 在“库”代码中使用ConfigureContext(false),即List 中的每个await 实际上应该是await ... .ConfigureAwait(false);

    【讨论】:

    • 感谢斯蒂芬帮助我。它有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多