這是落實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); // this line will throw exception
}
private static void CollectionCollectionChanged2(object sender, NotifyCollectionChangedEventArgs e)
{
}
發音它'BlockReëntrancy' – 2013-08-05 15:21:01