无法在多线程中操作ObservableCollection [英] Can not operate ObservableCollection in multi threads

查看:159
本文介绍了无法在多线程中操作ObservableCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎ObservableCollection仅支持从UI线程添加,删除,清除操作,如果由NO UI线程操作,则抛出不支持异常.我试图重写ObservableCollection的方法,不幸的是,我遇到了很多问题. 任何人都可以为我提供一个可以由多线程操作的ObservableCollection示例吗? 非常感谢!

It seems the ObservableCollection only support add, remove, clear operation from the UI thread, It throw Not Support Exception if it is operated by a NO UI thread. I tried to override methods of ObservableCollection, unfortunatly, I met lots of problems. Any one can provide me a ObservableCollection sample which can be operated by multi-threads? Many thanks!

推荐答案

使用

Using the link provided by Kent, you could use the following code to modify a collection across threads:

while (!Monitor.TryEnter(_lock, 10))
{
   DoEvents();
}

try
{
   //modify collection
}
finally
{
   Monitor.Exit(_lock);
}

但是,如果您只是想修改原始线程上的集合,则可以尝试使用UI线程的回调.我通常会这样:

If however you're just looking to modify the collection on your original thread you can try using a callback to your UI thread. I normally do something like this:

this.Dispatcher.Invoke(new MyDelegate((myParam) =>
{
  this.MyCollection.Add(myParam);
}), state);

这篇关于无法在多线程中操作ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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