Issues updating an ObservableCollection from a background thread

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:
- Create simple lock object in view model: object agentRTDataLock = new object();
- In constructor of view model, enable collection synchronization: BindingOperations.EnableCollectionSynchronization(RealTimeAgentData, agentRTDataLock);
- 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?
This is one way I have tried to use the dispatcher:
The exception does not give a line of where it occurred which is why I am struggling with this. It will go through method fine but then throw straight after, likely when the control is updated based on the new collection.
Probably this usage of dispatcher reduces the parallelism. Maybe you can do something like this in your thread:
Also check if it works when you assign some simple sample data to RealTimeAgentData. (The values must be built inside the action).
In the title to the question you are saying you are getting an exception updating an observable collection but it looks like you are using an generic list
Is there any other code that converts the list to an observable collection?
Can you clarify what you mean by 'The values must be built inside the action'? This would then run on the UI thread which would defeat the purpose.
Sorry I changed it to an ObservableCollection. I have changed back and forth to try different things.
Hi, @Matt Norman . Is there an update to this question? Could you show us the download link of your project or the complete code of your project for us to analyze and test?
Sign in to comment