Public ObservableCollection<T> SharedObj=new ObservableCollection<T>();
Thread mainThread = new Thread(() => MainThreadMethod(SharedObj);
mainThread.Start();
private DispatcherTimer _graphPlottingTimer=new DispatcherTimer();
_graphPlottingTimer.Tick += new EventHandler(_graphPlottingTimer_Tick);
_graphPlottingTimer.Interval = TimeSpan.FromMilliseconds(100);
_graphPlottingTimer.Start();
private void MainThreadMethod(ObservableCollection<T> obj)
{
//here i am adding rows in obj .
}
void _graphPlottingTimer_Elapsed(object sender, ElapsedEventArgs e)
{
private List<T> refinedList=new List<T>();
//I am getting a Collection Modify Exception on the below line
refinedList =SharedObj.Where(condition).ToList();
}
我正在收集修改的的最后一行例外_graphPlottingTimer_Elapsed上述方法。分享的对象,在多发线程
我试着锁和Dispatcher.CurrentDispatcher.BeginInvoke与_graphPlottingTimer_Elapsed 但它仍然给予相同的例外。
锁(thislock){refinedList = SharedObj.Where(condition).ToList();} –
但这不适合我,你可以请给其他解决方案。 thnks –
您正在修改MainThreadMethod中的集合,是吗?您还需要将其锁定在那里:每当您访问obj时,都需要使用锁定列表的同一字段来锁定它。 此外,为线程安全声明SharedObj静态。 –