Home > Article > Backend Development > How to Resolve \"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread\"?
Error: "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread"
Problem:
The error occurs when modifying an ObservableCollection on a thread other than the UI thread.
Solution:
1. Using Dispatcher.Invoke:
To update the ObservableCollection from a different thread, invoke the changes on the UI thread using Dispatcher.Invoke.
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); }); } }
2. Using async/await:
Alternatively, you can use async/await to execute the Load method asynchronously on the UI thread.
public void LoadAsync() { Task.Run(async () => { matchList = new List<GetMatchDetailsDC>(); matchList = await proxy.GetMatchAsync(); await Dispatcher.InvokeAsync(() => { foreach (EfesBet.DataContract.GetMatchDetailsDC match in matchList) { _matchObsCollection.Add(match); } }); }); }
DataGrid Binding and Refreshing:
Binding:
<DataGrid ItemsSource="{Binding MatchObsCollection}"/>
Refreshing Asynchronously:
To refresh the DataGrid asynchronously, call the Refresh method on the dispatcher in a delegate.
public void RefreshDataGridAsync() { Task.Run(() => { Dispatcher.InvokeAsync(() => { dataGridParent.ItemsSource = null; dataGridParent.ItemsSource = MatchObsCollection; }); }); }
The above is the detailed content of How to Resolve \"This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread\"?. For more information, please follow other related articles on the PHP Chinese website!