Updating an ObservableCollection in a separate thread
.Net 4.5 provides a solution within the BindingOperations class.
You can now use the BindingOperations.EnableCollectionSynchronization method as follows:
private readonly object _personCollectionLock;
private ObservableCollection<Person> _personCollection;
public ObservableCollection<Person> PersonCollection
{
get { return _personCollection; }
set
{
_personCollection = value;
BindingOperations.EnableCollectionSynchronization(_personCollection, _personCollectionLock);
}
I have only just tried this in my development environment but everything seems to be working correctly now when I update the collection from a background thread.
There is a more in-depth discussion of this solution at: http://10rem.net/blog/2012/01/16/wpf-45-observable-collection-cross-thread-change-notification
The MSDN entry for this method is at: https://msdn.microsoft.com/en-us/library/system.windows.data.bindingoperations.enablecollectionsynchronization(v=vs.110).aspx
With the built-in ObservableCollection<T>
class, you can't change the content from a separate thread if the UI is bound to the collection, it throws a NotSupportedException
(but change notification for properties of collection items works fine). I wrote an AsyncObservableCollection<T>
class to handle this case. It works by invoking the event handlers on the UI synchronization context