Created
January 19, 2012 06:32
-
-
Save saga/1638415 to your computer and use it in GitHub Desktop.
Check Reentrancy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Serializable] | |
private class SimpleMonitor : IDisposable | |
{ | |
private int _busyCount; | |
public bool Busy | |
{ | |
get | |
{ | |
return this._busyCount > 0; | |
} | |
} | |
public void Enter() | |
{ | |
this._busyCount++; | |
} | |
public void Dispose() | |
{ | |
this._busyCount--; | |
} | |
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] | |
public SimpleMonitor() | |
{ | |
} | |
} | |
private ObservableCollection<T>.SimpleMonitor _monitor = new ObservableCollection<T>.SimpleMonitor(); | |
protected IDisposable BlockReentrancy() | |
{ | |
this._monitor.Enter(); | |
return this._monitor; | |
} | |
protected void CheckReentrancy() | |
{ | |
if (this._monitor.Busy && this.CollectionChanged != null && this.CollectionChanged.GetInvocationList().Length > 1) | |
{ | |
throw new InvalidOperationException(SR.GetString("ObservableCollectionReentrancyNotAllowed")); | |
} | |
} | |
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) | |
{ | |
if (this.CollectionChanged != null) | |
{ | |
using (this.BlockReentrancy()) | |
{ | |
this.CollectionChanged(this, e); | |
} | |
} | |
} | |
protected override void RemoveItem(int index) | |
{ | |
this.CheckReentrancy(); | |
T t = base[index]; | |
base.RemoveItem(index); | |
this.OnPropertyChanged("Count"); | |
this.OnPropertyChanged("Item[]"); | |
this.OnCollectionChanged(NotifyCollectionChangedAction.Remove, t, index); | |
} | |
protected override void InsertItem(int index, T item) | |
{ | |
this.CheckReentrancy(); | |
base.InsertItem(index, item); | |
this.OnPropertyChanged("Count"); | |
this.OnPropertyChanged("Item[]"); | |
this.OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment