c# – 使用BindingOperations.EnableCollectionSynchronization
时间 2018-09-26
标签 c# collections multithreading observablecollection wpf 栏目 C#
原文 https://stackoverflow.com/questions/21720638/using-bindingoperations-enablecollectionsynchronization
我有两个WPF应用程序“UI”,“调试器”和一个ClassLibrary“BL”. UI对Debugger和BL的引用.调试器引用BL.
我在BL中收集了名为MyCollection的集合. UI应用程序启动调试器应用程序,调试器绑定到BL中的集合MyCollection.当我尝试从UI应用程序更改MyCollection集合时,我遇到异常.
A first chance exception of type 'System.NotSupportedException' occurred in PresentationFramework.dll Additional information: This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.
我在谷歌上搜索,发现:BindingOperations.EnableCollectionSynchronization
我无法弄清楚如何使用它.我不想引用我的BL项目中的任何UI dll.任何人都能协助我吗?
谢谢您的帮助!
我在Stack Overflow上看到的所有示例都是错误的.从其他线程修改集合时,必须锁定集合.
在调度程序(UI)线程上:
_itemsLock = new object(); Items = new ObservableCollection<Item>(); BindingOperations.EnableCollectionSynchronization(Items, _itemsLock);
然后从另一个线程:
lock (_itemsLock) { // Once locked, you can manipulate the collection safely from another thread Items.Add(new Item()); Items.RemoveAt(0); }
本文中的更多信息:http://10rem.net/blog/2012/01/20/wpf-45-cross-thread-collection-syn