Share via

How to change the ViewModel data from a thread?

mc 7,186 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?

Developer technologies | .NET | Xamarin
0 comments No comments

Answer accepted by question author

Anonymous
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.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

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