【问题标题】:How to await for an PostAsync method in xamarin?如何在 xamarin 中等待 PostAsync 方法?
【发布时间】: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


【解决方案1】:

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。这是一种特别适用于事件处理程序的应对措施。 “让异步运行”

【讨论】:

  • 无效,第4步仍然在第3步之前执行
  • 那么您在某处缺少await
  • 是的,我忘了一个等待,现在终于可以了,谢谢
猜你喜欢
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多