ObservableCollection 和线程
我的班级中有一个 ObservableCollection
。在我的课堂上,我有一个话题。我想从这个线程添加到我的 ObservableCollection
中。但我不能这样做:
这种类型的 CollectionView 不支持从与 Dispatcher 线程不同的线程更改其 SourceCollection。
请注意,这不是在 UI 线程中发生的,因此我无权访问调度程序。
I have an ObservableCollection
in my class. And further into my class I have a thread. From this thread I would like to add to my ObservableCollection
. But I can't do this:
This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.
Note that this is not happening from the UI thread, so i don't have access to the dispatcher.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
JaredPar 的方法是有效的。另一种值得考虑的方法是使用线程安全的 ObservableCollection 而不是内置的 ObservableCollection。有一些实现,但是 Sasha Barber 的实现 和 CLinq Continuous Collection 类 在我看来是一些更好的类。在内部,这些类本质上使用 JaredPar 概述的方法,但将其封装在集合类中。
JaredPar's approach is a valid one. Another approach which is worth considering is using a thread safe
ObservableCollection
instead of the built-inObservableCollection
. There's a few implementations out there, but Sasha Barber's implementation and the CLinq Continuous Collection class are some of the better ones in my opinion. Internally, these classes essentially use the approach outlined by JaredPar, but encapsulate it inside the collection class.解决此问题的最佳方法是将 Dispatcher 对象传递给后台线程的 start 方法。
现在,稍后当您需要添加到集合时,您可以使用 UI
Dispatcher
对象。正如 @Reed 指出的,更通用的解决方案是通过使用 SynchronizationContext 实现的。以下是使用
SynchronizationContext
创建负责添加新值的委托的函数样式示例。这样做的优点是从创建对象的代码中隐藏集合和线程模型。The best way to solve this is to pass the
Dispatcher
object to the start method of the background thread.Now later on when you need to add to the collection you can use the UI
Dispatcher
object.As @Reed pointed out, a more general solution is achieved by using
SynchronizationContext
. Here's a functional style sample usingSynchronizationContext
to create a delegate responsible for adding new values. This has the advantage of hiding both the collection and the threading model from the code creating the object.在.Net 4.5中,您可以使用线程安全集合、ConcurrentDictionary、ConcurrentBag等,无论哪个适合您的需求:http://msdn.microsoft.com/en-us/library/dd997305.aspx
另请考虑阅读:http://www.codeproject.com/Articles/208361/Concurrent-Observable-Collection-Dictionary-and-So
In.Net 4.5, you can use the Thread-safe collections, ConcurrentDictionary, ConcurrentBag etc, whichever suits your needs : http://msdn.microsoft.com/en-us/library/dd997305.aspx
Please consider reading also : http://www.codeproject.com/Articles/208361/Concurrent-Observable-Collection-Dictionary-and-So