Skip to content

Instantly share code, notes, and snippets.

@saga
Created January 19, 2012 06:32
Show Gist options
  • Save saga/1638415 to your computer and use it in GitHub Desktop.
Save saga/1638415 to your computer and use it in GitHub Desktop.
Check Reentrancy
[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