Xamarin Forms,使用async来应用ListView ItemSource

我目前正在使用Xamarin Forms,我使用的是从github RESTAPI获得的post方法。 每当我尝试将数据应用到ListView ItemsSource时,我的应用程序崩溃。

以下是当前执行的成功回调,它检索JSON并将其序列化并将其存储在名为listData的列表中。

 public class Home : ContentPage { private ListView myListView; private List listInfo = new List { }; RESTAPI rest = new RESTAPI(); Uri address = new Uri("http://localhost:6222/testBackEnd.aspx"); public Home () { Dictionary data = new Dictionary(); rest.post(address, data, success, null); Content = new StackLayout { Children = { myListView } }; } public void success(Stream stream) { DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List)); listData = (List)sr.ReadObject(stream); //myListView.ItemsSource = listData; } } 

是因为它不是异步的,如果是这样,我怎么能使这个方法异步? 我之前在Windows Phone 8.1上使用以下等待代码做了一个,是否有可用的Xamarin Forms等效代码?

 async public void success(Stream stream) { DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List)); listData = (List)sr.ReadObject(stream); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { myListView.ItemsSource = listData; }); } 

如果是因为它是异步的,那么你应该在主线程中进行UI更改(总是)。 为此:

 using Xamarin.Forms; ... Device.BeginInvokeOnMainThread(()=>{ // do the UI change } 

如果这不能解决它,那么异步不是(唯一的?)问题。

你可以尝试这种方式:

  Task.Run(()=> { downloadAllInformation(); Device.BeginInvokeOnMainThread( ()=> { myListView.ItemSource = ... }); }); 

通过这种方式,您可以异步管理listView的填充。

我用大量数据试过这个,性能更好。