Tuesday, May 16, 2017

WPF Tip #10 - Update ObservableCollection From a Background Thread

Pete Brown has a detailed blog post about updating ObservableCollection from background threads. I wanted to share the link to his post from 2012 and share a quick code snippet that illustrates how to do this in .NET 4.5 and later.

Before .NET 4.5, background updates to an ObservableCollection had to dispatch calls to the UI thread. Now all that is required is making a single call after initializing the collection in your ViewModel or other .NET class:

public ObservableCollection<MyObservableType> MyObservableCollection { get; set; }
 
private object _myCollectionLock = new object();
 
public MainViewModel()
{
    MyObservableCollection = new ObservableCollection<MyObservableType>();
 
    BindingOperations.EnableCollectionSynchronization(MyObservableCollection, _myCollectionLock);
}

Go check out Pete's post with the full details.

Cheers!

del.icio.us Tags: ,,