【发布时间】:2022-01-27 15:42:50
【问题描述】:
我正在尝试在 xamarin 项目中执行 await client.PostAsync() 之类的操作,但它不会等待。我怎样才能让它等待? 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;
}
我需要的是按正确的顺序执行这些步骤(// 代码的 cmets 中的步骤 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 运行完全相同的代码,它确实在等待。
【问题讨论】:
-
您有什么特别的原因要避免使用
await/async?如果您有需要它的代码,通常最好使用它们,并且如果您需要在代码中进一步实现它,那么也这样做。 -
@DudeManGuy 我这样做的原因是我从我的 testclient 中复制了 winforms 中的代码,我没有这个问题。你能告诉我一个如何做你建议的例子吗?
-
您应该等待“步骤 1”中的
Task完成,然后再执行“步骤 4”。
标签: c# xamarin xamarin.forms async-await