Issues updating an ObservableCollection from a background thread

Matt Norman 1 Reputation point
2022-01-18T11:33:32.16+00:00

I am attempting to run my data collection process in a background thread and then update an ObservableCollection that is bound to a DataGrid.

I have tried most different solutions that I have found around the web and unfortunately all keep leading me back to an exception:

System.ArgumentException: 'Must create DependencySource on same Thread as the DependencyObject.'

I have created a test project that uses a new thread to get data and then updates the collection and it all works fine.

As soon as I do the same thing in my main project I just get the exception again.

The exception doesn't really point me to where the issue is so i'm not even sure i'm looking in the right place.

The method I am currently using is as follows:

  1. Create simple lock object in view model: object agentRTDataLock = new object();
  2. In constructor of view model, enable collection synchronization: BindingOperations.EnableCollectionSynchronization(RealTimeAgentData, agentRTDataLock);
  3. In new thread, get new data and update collection: RealTimeAgentData = DataManagerRealTimeAgent.GetAgentData(selectedGroups);

I have also tried invoking the current dispatcher to update the collection but still get the same thing. I have also tried locking the object and that also gives me the same excpetion.

Does anyone have any ideas?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,710 questions
{count} votes