Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms: Should ObservableCollection always be set/updated in the UI thread?

Recently, I had to implement infinite scrolling / lazy loading on my PCL ListView. I will leave out most of the code, but the most important part was:

ViewModel

   var countries = // get countries
   foreach (var country in countries)
   {
        // Countries is an ObservableCollection<Country> 
        Countries.Add(country);
   }

This seemed to work fine on Android, but on iOS, I kept getting out of range exceptions especially when I scrolled the list fast. The fix for me was to run this code in the main UI thread.

// wrap the code with this
Device.BeginInvokeOnMainThread(async () => {});

My question now is should all view model service calls that update or set an observable collection be always executed in the UI thread?

I have several commands that set Countries. They seem to work fine without the UI thread block. I only had issues with adding items as indicated above.

Should ObservableCollection always be set and updated in the UI thread?

like image 486
Mark13426 Avatar asked Sep 04 '16 19:09

Mark13426


1 Answers

ObservableCollection itself isn't thread-safe. However you can change ViewModel properties (ObservableCollections among them) from non-UI thread, because the code updating properties of the UI Views itself will be run on the UI thread. Xamarin will take care of it itself. Try using thread-safe ObservableCollection.

like image 127
nicks Avatar answered Oct 17 '22 14:10

nicks