如何使的ObservableCollection线程安全的? [英] How to make ObservableCollection thread-safe?

查看:1386
本文介绍了如何使的ObservableCollection线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.



我添加/从一个ObservableCollection这是不是在UI线程删除。

I am adding/removing from an ObservableCollection which is not on a UI thread.

我有一个方法名EnqueueReport添加到colleciton和DequeueReport从colleciton除去

I have a method names EnqueueReport to add to the colleciton and a DequeueReport to remove from the colleciton.

的步骤的流如下图所示: -

The flow of steps is as below :-


  1. 1.call EnqueueReport每当一个新的报告要求

  2. 调用一个方法每隔几秒钟检查是否生成报告(这有一个foreach循环检查的的ObservableCollection所有报告生成的状态)

  3. 调用DequeueReport如果生成的报告

我没有太多的C#库。是否有人可以指导我一下吗?

I am not much in C# libraries. Can someone please guide me on this?

推荐答案

您可以创建一个可观察的集合中的一个简单的线程友好的版本。如下所示:

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

 public class MTObservableCollection<T> : ObservableCollection<T>
    {
        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);
                }
        }
    }



与现在要做一个巨大的查找和放大器;替换和更改所有的ObservableCollection MTObservableCollection 和你的好去。

这篇关于如何使的ObservableCollection线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆