Home > Article > Backend Development > How to Modify an ObservableCollection From a Non-Dispatcher Thread in WPF?
A DataGrid bound to an asynchronously populated ObservableCollection throws an error stating that changes to the SourceCollection are not permitted from a non-Dispatcher thread.
The problem arises from thread affinity. The ObservableCollection is initially created on the UI thread, making it accessible only from the UI thread. To modify it from a different thread, the delegate must be placed on the UI Dispatcher.
<code class="csharp">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); }); } }</code>
By invoking the delegate on the UI Dispatcher, the additions to the ObservableCollection are scheduled on the UI thread, resolving the exception.
For asynchronous binding and refreshing of the DataGrid, consider using INotifyPropertyChanged on your ViewModel properties and invoking the Dispatcher to refresh the UI elements.
The above is the detailed content of How to Modify an ObservableCollection From a Non-Dispatcher Thread in WPF?. For more information, please follow other related articles on the PHP Chinese website!