在進行WPF開發過程當中,須要從一個新的線程中操做ObservableCollection,結果程序拋出一個NotSupportedException的
錯誤ide
public class AsyncObservableCollection<T> : ObservableCollection<T> { //獲取當前線程的SynchronizationContext對象 private SynchronizationContext _synchronizationContext = SynchronizationContext.Current; public AsyncObservableCollection() { } public AsyncObservableCollection(IEnumerable<T> list) : base(list) { } protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (SynchronizationContext.Current == _synchronizationContext) { //若是操做發生在同一個線程中,不須要進行跨線程執行 RaiseCollectionChanged(e); } else { //若是不是發生在同一個線程中 //準確說來,這裏是在一個非UI線程中,須要進行UI的更新所進行的操做 _synchronizationContext.Post(RaiseCollectionChanged, e); } } private void RaiseCollectionChanged(object param) { // 執行 base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param); } protected override void OnPropertyChanged(PropertyChangedEventArgs e) { if (SynchronizationContext.Current == _synchronizationContext) { // Execute the PropertyChanged event on the current thread RaisePropertyChanged(e); } else { // Post the PropertyChanged event on the creator thread _synchronizationContext.Post(RaisePropertyChanged, e); } } private void RaisePropertyChanged(object param) { // We are in the creator thread, call the base implementation directly base.OnPropertyChanged((PropertyChangedEventArgs)param); } }
https://blog.csdn.net/juns6/article/details/50964496spa