"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."
//this exception is thrown because ObservableCollections (OCs) cannot have their
//collections modified from any thread but the UI thread. See linked source.
// -- To make OCs thread-safe in WPF 4.5+ :
//as a field in class where OC is instantiated:
using System.Collections.ObjectModel; //for ObservableCollection<T>
using System.Windows.Data; //for BindingOperations
using System.Windows;
using System.Threading;
public static object m_lockObject; //NOTE: One lockObject per collection!
public static ObservableCollection<T> m_OC;
//where OC is created (typically the constructor)
OC = new ObservableCollection<T>();
BindingOperations.EnableCollectionSynchronization(m_OC, m_lockObject);
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Send,
new Action(() => {
BindingOperations.EnableCollectionSynchronization(m_OC, m_lockObject);
}));
//the call of the EnableCollectionSynchronization MUST happen on the UI thread.
//This Dispatcher action ensures that it does.
//-- FINALLY --
//when altering OC will trigger OnPropertyChanged (.Add(), .Clear(), etc.)
//encase such statements within a lock using that OC's lockObject
lock (m_lockObject)
{
m_OC.Add(null);
}