GetAsync:不返回 HttpResponseMessage

GetAsync : not returning HttpResponseMessage

应用程序应该从 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;
            }
        }
    }

请帮忙!

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

So this is what happens, starting with the top-level method (Button1_Click for UI / MyController.Get for ASP.NET):

  1. The top-level method calls GetJsonAsync (within the UI/ASP.NET context).

  2. GetJsonAsync starts the REST request by calling HttpClient.GetStringAsync (still within the context).

  3. GetStringAsync returns an uncompleted Task, indicating the REST request is not complete.

  4. GetJsonAsync awaits the Task returned by GetStringAsync. The context is captured and will be used to continue running the GetJsonAsync method later. GetJsonAsync returns an uncompleted Task, indicating that the GetJsonAsync method is not complete.

  5. The top-level method synchronously blocks on the Task returned by GetJsonAsync. This blocks the context thread.

  6. … Eventually, the REST request will complete. This completes the Task that was returned by GetStringAsync.

  7. The continuation for GetJsonAsync is now ready to run, and it waits for the context to be available so it can execute in the context.

  8. Deadlock. The top-level method is blocking the context thread, waiting for GetJsonAsync to complete, and GetJsonAsync is waiting for the context to be free so it can complete.

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

  1. In your “library” async methods, use ConfigureAwait(false) wherever possible.
  2. Don’t block on Tasks; use async all the way down.

方案二建议将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..");
    }            
}