我正在嘗試await client.PostAsync()在 xamarin 專案中做一些事情,但它不會等待。我怎樣才能讓它等待?winforms 專案中的相同代碼確實等待。
我的代碼
private bool ConfirmLogin(string user, string password)
{
bool result = false;
AppLoginRequest appLoginRequest = new AppLoginRequest();
AppLoginResponse appLoginResponse = new AppLoginResponse();
// step 1
Task<HttpResponseMessage> task = GetAppLogin(appLoginRequest, appLoginResponse);
// step 4
result = appLoginResponse.Authorized;
return result;
}
和 GetAppLogin 的代碼
private async Task<HttpResponseMessage> GetAppLogin(AppLoginRequest appLoginRequest, AppLoginResponse appLoginResponse)
{
HttpResponseMessage response = null;
string JsonData = JsonConvert.SerializeObject(appLoginRequest);
System.Net.Http.StringContent restContent = new StringContent(JsonData, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
try
{
// step 2
response = await client.PostAsync(@"http://x.x.x.x:xxxx/api/XXX/GetAppLogin", restContent);
// step 3
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadAsStringAsync();
AppLoginResponse Result = JsonConvert.DeserializeObject<AppLoginResponse>(stream);
}
else
{
appLoginResponse.Remark = response.ReasonPhrase;
}
}
catch (Exception ex)
{
appLoginResponse.Authorized = false;
appLoginResponse.Remark = ex.Message;
}
return response;
}
我需要的是按正確的順序執行步驟(// 代碼注釋中的步驟 x)。
Step 1, then step 2, then step 3 and finally step 4
但它是這樣執行的
step 1 then step 2 and then step 4 and step 3
這當然弄亂了完整的邏輯,有沒有辦法我可以強制client.PostAsync真正等待?
我發現了數百個關于如何同步運行異步任務的問題,但似乎都不起作用。
xamarin 對此有何不同?
我從一個用 winforms 撰寫的 testclient 運行完全相同的代碼,它確實在等待。
uj5u.com熱心網友回復:
async void ButtonClick(...)
{
bool x = await ConfirmLogin(..., ...);
}
private async Task<bool> ConfirmLogin(string user, string password)
{
bool result = false;
AppLoginRequest appLoginRequest = new AppLoginRequest();
AppLoginResponse appLoginResponse = new AppLoginResponse();
// step 1
await GetAppLogin(appLoginRequest, appLoginResponse);
// step 4
result = appLoginResponse.Authorized;
return result;
}
async void在可以避免的情況下不要使用。這是一個特別適用于事件處理程式的 cop-out。“讓異步運行”
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/396909.html
標籤:C# 沙马林 xamarin.forms 异步等待
