7

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?

Mark13426
  • 2,569
  • 6
  • 41
  • 75

1 Answers1

1

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.

nicks
  • 2,161
  • 8
  • 49
  • 101
  • 1
    Thanks. If Xamarin handles thread switching, why should I use a thread-safe ObservableCollection? – Mark13426 Sep 07 '16 at 00:11
  • Because **you** might wanna modify it from different threads. – nicks Sep 07 '16 at 05:44
  • it is guaranteed that Xamarin will update UI objects (based on changes in VM) on the UI thread. it's up to you to update VM on the same thread though, or use thread-safe objects. – nicks Sep 07 '16 at 08:07
  • 1
    Re *"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"* - that makes no sense to me. No, you *can't* **safely** add/remove elements of your ObservableCollections from a background thread - if the UI code is in the middle of layout, enumerating that collection, and your thread gets a chance to run, you will get a collection modified exception. That's happening in my code right now. Don't assume UI thread always completes its task before being suspended. – ToolmakerSteve Apr 18 '20 at 00:52