ObservableCollection安全集合的正确使用

我在Stack Overflow上看到的所有示例都是错误的.从其他线程修改集合时,必须锁定集合.

在调度程序(UI)线程上:

_itemsLock = new object();

//创建ObservableCollection
Items = new ObservableCollection();

//使集合在多个线程中捕获并指定应该使用同步对集合的访问的锁定对象。
BindingOperations.EnableCollectionSynchronization(Items, _itemsLock);
然后从另一个线程:
lock (_itemsLock)
{
    // Once locked, you can manipulate the collection safely from another thread
    Items.Add(new Item());
    Items.RemoveAt(0);
}
 

你可能感兴趣的:(WPF)