在多线程环境中使用ObservableCollection的最佳方法

时间:2014-08-12 00:55:32

标签: c# wpf multithreading observablecollection

从下面确定哪一个是最好的方法还是其他更好的方法?

两者都在工作(学分不属于我)

public static MTObservableCollection<string> ocEventsCollection = new MTObservableCollection<string>();

    public static void AddMsgToEvents(string srMessage)
    {
        lock (ocEventsCollection)
            ocEventsCollection.Insert(0, srMessage);

    }

    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);
                }
        }
    }

第二种方法

public static ObservableCollection<string> ocEventsCollection = new ObservableCollection<string>();



public static void AddMsgToEvents(string srMessage)
{
    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
    {
        ocEventsCollection.Insert(0, srMessage);
    }));
}

0 个答案:

没有答案