What's the best way to update an ObservableCollection from another thread?

Joan Venge picture Joan Venge · Mar 30, 2011 · Viewed 32.5k times · Source

I am using the BackgroundWorker to update an ObservableCollection but it gives this error:

"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."

What's the best and most elegant way to solve this, with the least amount of work. I don't want to write low level lock-based multi-threading code.

I have seen some solutions online but they are several years old, so not sure what the latest consensus is for the solution of this problem.

Answer

ywm picture ywm · Aug 30, 2011

If you initialize the collection in the constructor it will be on the default Application thread.

To invoke the main thread you can do this:

Application.Current.Dispatcher.Invoke((Action)(() =>
    {
       //Do something here.
    }));

You have to cast the Anonymous delegate as an action otherwise it gets confused ¯\O_o/¯

If you are using the Async CTP then you can do this

Application.Current.Dispatcher.InvokeAsync(()=>
    {
       //Do something here.
    });