Dispatcher Thread Affinity Violation with ObservableCollection Modification
In a WPF application, certain types of collections, including DataGrid, must be modified from the Dispatcher thread. This is because these collections maintain an affinity with the UI thread, and attempting to modify them from a different thread can lead to exceptions like "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."
In the provided code, the ObservableCollection _matchObsCollection in the MainWindowViewModel is created on the UI thread. However, the Load() method, which modifies this collection, is called asynchronously. This causes the exception because the modification is attempted from a thread other than the UI thread.
Solution:
To resolve the issue, any modifications to _matchObsCollection must be performed on the Dispatcher thread. This can be achieved by using the Dispatcher.Invoke() method to delegate the modifications to the UI thread.
Here is a modified version of the Load() method that uses Dispatcher.Invoke() to modify the ObservableCollection on the UI thread:
public void Load() { matchList = new List<GetMatchDetailsDC>(); matchList = proxy.GetMatch().ToList(); foreach (EfesBet.DataContract.GetMatchDetailsDC match in matchList) { App.Current.Dispatcher.Invoke((Action)delegate { _matchObsCollection.Add(match); }); } }
This modified code ensures that all modifications to _matchObsCollection are delegated to the UI thread, resolving the exception.
The above is the detailed content of How Can I Modify an ObservableCollection from a Different Thread in a WPF Application Without a Dispatcher Thread Affinity Violation?. For more information, please follow other related articles on the PHP Chinese website!