[英]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線程並導致死鎖。 從Stephen Cleary的博客中 (只需用LoginUser
方法替換GetJsonAsync
,並用client.GetAsync
替換GetStringAsync
):
因此,這是從頂級方法(UI的Button1_Click / ASP.NET的MyController.Get)開始發生的事情:
頂級方法調用GetJsonAsync(在UI / ASP.NET上下文中)。
GetJsonAsync通過調用HttpClient.GetStringAsync(仍在上下文中)來啟動REST請求。
GetStringAsync返回一個未完成的任務,指示REST請求未完成。
GetJsonAsync等待GetStringAsync返回的任務。 上下文被捕獲,以后將用於繼續運行GetJsonAsync方法。 GetJsonAsync返回一個未完成的Task,指示GetJsonAsync方法未完成。
頂級方法同步阻止GetJsonAsync返回的Task。 這將阻塞上下文線程。
…最終,REST請求將完成。 這就完成了GetStringAsync返回的任務。
GetJsonAsync的延續現在可以運行了,它等待上下文可用,以便可以在上下文中執行。
僵局。 頂級方法正在阻止上下文線程,等待GetJsonAsync完成,而GetJsonAsync正在等待上下文空閑以便可以完成。
和簡單的可用解決方案(也來自博客):
- 在“庫”異步方法中,盡可能使用ConfigureAwait(false)。
- 不要阻塞任務; 一直使用異步。
button1_Click
解決方案建議您將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..");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.