Should I use the dispatcher object if I want to update ObservableCollection on the worker or background thread?
Then why does this work:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
for (int i = 0; i < 10000000; i++)
{
Data.Add("1");
}
Task.Run(() =>
{
Data.Clear();
});
}
public ObservableCollection<string> Data
{
get => _data;
set
{
_data = value;
OnPropertyChanged();
}
}
private ObservableCollection<string> _data = new ObservableCollection<string>();
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
But this code throws an exception (at Data.Clear();): System.NotSupportedException: 'This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.'
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
for (int i = 0; i < 10000000; i++)
{
Data.Add("1");
}
Task.Run(() =>
{
Data.Clear();
});
}
public ObservableCollection<string> Data
{
get => _data;
set
{
_data = value;
OnPropertyChanged();
}
}
private ObservableCollection<string> _data = new ObservableCollection<string>();
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
In the first example we Clear ObservableCollection from the NON UI Thread as well as in the second. But the iterations count was lower. Can anyone explain the problem? I just want to add and clear items in the Collection.