简体   繁体   中英

Xamarin Forms, using async to apply ListView ItemSource

I am currently using Xamarin Forms and I am using the post method which I got from github RESTAPI . My application crashes whenever I try to apply the data to my ListView ItemsSource.

The following is the success callback that is currently executed, and it retrieves the JSON and serialize it and storing it in a list called listData.

public class Home : ContentPage
{
    private ListView myListView;
    private List<Person> listInfo = new List<Person> { };

    RESTAPI rest = new RESTAPI();
    Uri address = new Uri("http://localhost:6222/testBackEnd.aspx");

    public Home ()
    {
        Dictionary<String, String> data = new Dictionary<String, String>();
        rest.post(address, data, success, null);

        Content = new StackLayout { 
            Children = 
            {
                myListView
            }
        };
    }

    public void success(Stream stream)
    {
        DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List<Person>));
        listData = (List<Person>)sr.ReadObject(stream);
        //myListView.ItemsSource = listData;
    }
}

Is it because it is not asynchronous, and if so how can I make this method asynchronous? I did one previously on Windows Phone 8.1 using the following await code, is there a Xamarin Forms equivalent available for it?

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

you can try with this way:

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

         });

in this way you manage asynchronously the filling of listView.

I've tried this with a lot of data and the performances are better.

If it is because it is asynchronous, then you should do the UI change (always) in the main thread. To do so:

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

If this doesn't solve it, then async is not the (only?) problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM