How to make ObservableCollection thread-safe?

前端 未结 4 863
天命终不由人
天命终不由人 2020-11-29 03:42
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

I am adding/removing from an ObservableCollection

4条回答
  •  余生分开走
    2020-11-29 04:02

    You can create a simple thread friendly version of the observable collection. Like the following :

     public class MTObservableCollection : ObservableCollection
        {
            public override event NotifyCollectionChangedEventHandler CollectionChanged;
            protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
            {
                NotifyCollectionChangedEventHandler CollectionChanged = this.CollectionChanged;
                if (CollectionChanged != null)
                    foreach (NotifyCollectionChangedEventHandler nh in CollectionChanged.GetInvocationList())
                    {
                        DispatcherObject dispObj = nh.Target as DispatcherObject;
                        if (dispObj != null)
                        {
                            Dispatcher dispatcher = dispObj.Dispatcher;
                            if (dispatcher != null && !dispatcher.CheckAccess())
                            {
                                dispatcher.BeginInvoke(
                                    (Action)(() => nh.Invoke(this,
                                        new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))),
                                    DispatcherPriority.DataBind);
                                continue;
                            }
                        }
                        nh.Invoke(this, e);
                    }
            }
        }
    

    with that now do a massive find & replace and change all your ObservableCollection to MTObservableCollection and your good to go

提交回复
热议问题