这是实现BlockReentrancy()
的内容。
protected IDisposable BlockReentrancy()
{
this._monitor.Enter();
return this._monitor;
}
还有另一种方法CheckReentrancy()
protected void CheckReentrancy()
{
if ((this._monitor.Busy && (this.CollectionChanged != null)) && (this.CollectionChanged.GetInvocationList().Length > 1))
{
throw new InvalidOperationException(SR.GetString("ObservableCollectionReentrancyNotAllowed"));
}
}
在修改集合之前,ClearItems
、InsertItem
、MoveItem
、RemoveItem
、SetItem
等方法会检查CheckReentrancy()
。
因此,在using
块内保证集合不会被改变,但前提是订阅了多个处理程序到CollectionChanged
事件。
using BlockReentrancy())
{
CollectionChanged(this, e);
}
这个例子展示了BlockReentrancy()
的作用。
private static void Main()
{
collection.CollectionChanged += CollectionCollectionChanged1;
collection.CollectionChanged += CollectionCollectionChanged2;
collection.Add(1);
}
private static void CollectionCollectionChanged1(object sender, NotifyCollectionChangedEventArgs e)
{
collection.Add(2);
}
private static void CollectionCollectionChanged2(object sender, NotifyCollectionChangedEventArgs e)
{
}
BlockReëntrancy
。 - Colonel Panicusing (BlockReentrancy()) {}
。这可能仅涉及单个XAML绑定,而且在自定义代码中没有任何其他显式订阅者。 - DK.