How to change the ViewModel data from a thread?

mc 3,866 Reputation points

for example I have a viewmodel


public class IndexViewModel
    public ObservableCollection<Order>Items{get;set;}

I want create a thread .how to change the List in the thread?

A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,312 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 70,556 Reputation points Microsoft Vendor


    Welcome to our Microsoft Q&A platform!

    Do you want to achieve the thread-safe when we then try to update the collection from different threads, and want to get rid this error because ObservableCollection isn't thread safe:

    System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index

    If so, we can change the viewModel like following code. We just need to call this method in our constructor after initializing our ObservableCollection and our collection becomes thread safe:

       public class IndexViewModel  
               public IndexViewModel()  
                   Items = new ObservableCollection<Order>();  
                   Items.Add(new Order() { Name= "2222" });  
                   Items.Add(new Order() { Name = "3256" });  
                   Xamarin.Forms.BindingBase.EnableCollectionSynchronization(Items, null, ObservableCollectionCallback);  
               public ObservableCollection<Order> Items { get; }  
               void ObservableCollectionCallback(IEnumerable collection, object context, Action accessMethod, bool writeAccess)  
                   // `lock` ensures that only one thread access the collection at a time  
                   lock (collection)  

    Best Regards,

    Leon Lu

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

0 additional answers

Sort by: Most helpful