【问题标题】:Xamarin forms page doesn't load until async call is doneXamarin 表单页面在异步调用完成之前不会加载
【发布时间】:2018-11-13 04:17:46
【问题描述】:

我正在尝试打开一个新页面,该页面显示一个列表,其中填充了来自服务器的数据。从服务器获取数据的调用是使用从 OnAppearing 方法调用的异步函数完成的。但是,即使该方法是异步的,在调用完成之前我的 UI 页面也不会显示。我该如何解决这个问题或进行此调用的最佳做法是什么?

这是我的页面 XAML 代码:

<StackLayout>
  <Label
    x:Name="NoPostsMessage"
    Text="You have not created any posts yet :("
    VerticalOptions="CenterAndExpand"
    HorizontalOptions="CenterAndExpand" />

  <ListView
    x:Name="PostList"
    SelectionMode="None">
    <ListView.ItemTemplate>
      <DataTemplate>
        <TextCell Text="{Binding Text}" Detail="{Binding Detail}" />
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</StackLayout>

这是我的 C# 代码:

protected override void OnAppearing()
{
  base.OnAppearing();

  GetContributions();
}

async private void GetContributions()
{
  HttpClient client = new HttpClient();

  client.DefaultRequestHeaders.Add("Accept", "application/json");

  HttpResponseMessage response = await client
    .GetAsync
    (
      "websiteURL.com"
    );

  if (response.IsSuccessStatusCode)
  {
    APIResponse data = JsonConvert.DeserializeObject<APIResponse>(response.Content.ReadAsStringAsync().Result);
    if (data.ResponseCode == 1)
    {
      string payloadData = data.Data.ToString();
      List<TextCell> userPosts = JsonConvert.DeserializeObject<List<TextCell>>(payloadData);

      if (userPosts.Count == 0)
      {
        NoPostsMessage.IsVisible = true;
        PostList.IsVisible = false;
      }
      else
      {
        NoPostsMessage.IsVisible = false;
        PostList.IsVisible = true;

        ReportsList.ItemsSource = userPosts;
      }
    }
    else
    {
      await DisplayAlert("Error", data.ErrorMessage, "OK");
    }
  }
  else
  {
    await DisplayAlert("Error", "An error has occurred, please try again later", "OK");
  }
}

【问题讨论】:

  • 你为什么在async方法中使用.Result
  • @Cheesebaron,感谢您指出这一点。当我将方法更改为异步时,我忘了更改它。我会用等待替换它

标签: c# xaml xamarin xamarin.forms


【解决方案1】:

如果不使用awaitasync 调用会阻塞 UI

protected async override void OnAppearing()
{
  base.OnAppearing();

  await GetContributions();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2010-12-23
    • 2017-04-01
    相关资源
    最近更新 更多