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.