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

C# 在多线程环境中使用ObservableCollection的最佳方法,c#,wpf,multithreading,observablecollection,C#,Wpf,Multithreading,Observablecollection,好的,下面哪一个是最好的方法还是其他更好的方法 两人都在工作(学分不属于我) 公共静态MTObservableCollection OceventCollection=新MTObservableCollection(); 公共静态void AddMsgToEvents(字符串srMessage) { 锁(OCEventCollection) OceventCollection.Insert(0,srMessage); } 公共类MTObservableCollection:ObservableC

好的,下面哪一个是最好的方法还是其他更好的方法

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

公共静态MTObservableCollection OceventCollection=新MTObservableCollection();
公共静态void AddMsgToEvents(字符串srMessage)
{
锁(OCEventCollection)
OceventCollection.Insert(0,srMessage);
}
公共类MTObservableCollection:ObservableCollection
{
公共覆盖事件NotifyCollectionChangedEventHandler CollectionChanged;
CollectionChanged上的受保护覆盖无效(NotifyCollectionChangedEventArgs e)
{
NotifyCollectionChangedEventHandler CollectionChanged=this.CollectionChanged;
如果(CollectionChanged!=null)
foreach(CollectionChanged.GetInvocationList()中的NotifyCollectionChangedEventHandler nh)
{
DispatcherObject DispatcherJ=nh.Target作为DispatcherObject;
if(dispObj!=null)
{
Dispatcher Dispatcher=dispObj.Dispatcher;
if(dispatcher!=null&!dispatcher.CheckAccess())
{
调度程序。开始启动(
(Action)(()=>nh.Invoke(这个,
新建NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)),
DispatcherPriority.DataBind);
持续
}
}
调用(本,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);
    }));
}
publicstaticobservedcollection-oceventscolection=newobservedcollection();
公共静态void AddMsgToEvents(字符串srMessage)
{
Application.Current.Dispatcher.BeginInvoke(新操作(()=>
{
OceventCollection.Insert(0,srMessage);
}));
}

看看caliburn micro的BindableCollection“最佳方法”是什么意思?哪一个更“线程安全”?如果您考虑线程安全并使用framework 4.5,为什么不使用开箱即用的工具?查看
BindingOperations
并使用
EnableCollectionSynchronization
方法或使用
BlockingCollection()
public static ObservableCollection<string> ocEventsCollection = new ObservableCollection<string>();



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