How to change the ViewModel data from a thread?

mc 5,061 Reputation points
2021-09-06T02:25:07.743+00:00

for example I have a viewmodel

IndexViewModel:

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

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

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

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 78,511 Reputation points Microsoft Vendor
    2021-09-06T06:27:16.59+00:00

    Hello,​

    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)  
                   {  
                       accessMethod?.Invoke();  
                   }  
               }  
           }  
    

    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.