在Xamarin中加载布局异步

时间:2016-01-31 01:08:22

标签: c# xamarin mono async-await xamarin-forms

我正在尝试将内容加载到堆栈布局异步,但到目前为止还没有运气。

当我浏览页面时,我将元素添加到堆栈布局中。即使我在aysnc函数上执行它,我也会冻结,直到加载所有内容。我想显示一个活动指标。当指标旋转时,我想加载布局。

我在OnAppering方法上尝试了这个,但它没有用。

protected async override OnApperaing()
{
     base.OnApperaing();
     for(int i = 0; i < 100; i++)
     {
          stacklayout.Children.Add(new Label { Text = "Some Text" });
     }
}

我该如何处理?此致

1 个答案:

答案 0 :(得分:3)

您不是在等待任何方法,因此您的方法同步运行。

你应该收到警告,说明行之间的内容

  

异步方法缺少等待运算符......

根据您的情况,您需要执行类似的操作

protected async override void OnApperaing()
{
      base.OnApperaing();
      for(int i = 0; i < 100; i++)
      {
           await Task.Run(() => {
               var tcs = new TaskCompletionSource<bool>();
               InvokeOnMainThread(() => {
                  stacklayout.Children.Add(new Label { Text = "Some Text" });
                  tcs.SetResult(false);
               });

               return tcs.Task;
           });
      }
}