I'm working on a WPF application and found that property changed notifications on binded properties can happen from a background thread, however for making any change to an observablecollection(like adding or removing item) has to happen from a UI thread. My question is why is it so? Both INotifyPropertyChanged and INotifyCollectionChanged are subscribed by UI controls, then why an exception for INotifyPropertyChanged?
For example:
public class ViewModel : INotifyPropertyChanged
{
ObservableCollection<Item> _items = new ObservableCollection<Item>();
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
//Can fire this from a background thread without any crash and my
//Name gets updated in the UI
InvokePropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
public void Add(Item item)
{
//Cant do this from a background thread and has to marshal.
_items.Add(item);
}
public event PropertyChangedEventHandler PropertyChanged;
public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
}
NOTE: CollectionChanged event from a background thread crashes the app, however PropertyChanged event from a background thread updates the UI without any issues and yes, this is in .NET 4.0