【问题标题】:GetAsync : not returning HttpResponseMessageGetAsync:不返回 HttpResponseMessage
【发布时间】:2016-07-02 04:57:01
【问题描述】:

应用应该收到来自 LoginUser()httpresponsemessage,但它没有响应。

    private void button1_Click(object sender, EventArgs e)
    {
        if (LoginUser(tUser.Text, Password.Text).Result.IsSuccessStatusCode)
        {
            Notifier.Notify("Successfully logged in.. Please wait!");

        }
        else
        {
            Notifier.Notify("Please check your Credential..");
        }            
    }

    public async Task<HttpResponseMessage> LoginUser(string userid, string password)
    {
        string URI = "http://api.danubeco.com/api/userapps/authenticate";

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("c291cmF2OmtheWFs");

            using (var response = await client.GetAsync(String.Format("{0}/{1}/{2}", URI, userid, password)))
            {
                return response;
            }
        }
    }

请帮忙!

【问题讨论】:

标签: c# asynchronous async-await webapi2 httpresponsemessage


【解决方案1】:

您正在阻塞 UI 线程并导致死锁。 From Stephen Cleary's blog(只需将GetJsonAsync 替换为LoginUser 方法,将GetStringAsync 替换为client.GetAsync):

所以这就是发生的事情,从顶级方法开始 (Button1_Click 用于 UI / MyController.Get 用于 ASP.NET):

  1. 顶级方法调用 GetJsonAsync(在 UI/ASP.NET 上下文中)。

  2. GetJsonAsync 通过调用 HttpClient.GetStringAsync 启动 REST 请求(仍在上下文中)。

  3. GetStringAsync 返回未完成的Task,表示REST 请求未完成。

  4. GetJsonAsync 等待 GetStringAsync 返回的任务。上下文被捕获并将用于继续运行 GetJsonAsync 方法稍后。 GetJsonAsync 返回一个未完成的任务, 表示GetJsonAsync方法不完整。

  5. 顶级方法同步阻塞 GetJsonAsync 返回的任务。这会阻塞上下文线程。

  6. ... 最终,REST 请求将完成。这样就完成了 GetStringAsync 返回的任务。

  7. GetJsonAsync 的延续现在已准备好运行,它等待上下文可用,以便在上下文中执行。

  8. 死锁。顶层方法是阻塞上下文线程,等待GetJsonAsync完成,而GetJsonAsync正在等待 上下文是免费的,以便它可以完成。

以及简单的可用解决方案(也来自博客):

  1. 在“库”异步方法中,尽可能使用 ConfigureAwait(false)。
  2. 不要阻止任务;一直使用异步。

第二种解决方案建议您将button1_Click 更改为:

private async void button1_Click(object sender, EventArgs e)
{
    if ((await LoginUser(tUser.Text, Password.Text)).IsSuccessStatusCode)
    {
        Notifier.Notify("Successfully logged in.. Please wait!");

    }
    else
    {
        Notifier.Notify("Please check your Credential..");
    }            
}

【讨论】:

    猜你喜欢
    • 2017-08-09
    • 1970-01-01
    • 2022-11-12
    • 2015-02-21
    • 2016-05-20
    • 2023-04-02
    • 2013-11-26
    • 2014-09-09
    • 2023-03-08
    相关资源
    最近更新 更多