ObservableCollection+BindingOperations.EnableCollectionSynchronization

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值