Skip to content

Instantly share code, notes, and snippets.

@wgross
Last active January 23, 2017 06:48
Show Gist options
  • Save wgross/7977fc296f057825f0b5 to your computer and use it in GitHub Desktop.
Save wgross/7977fc296f057825f0b5 to your computer and use it in GitHub Desktop.
Provides a code section where a specified piece of code is executed on leave (and enter optionally)
public sealed class ScopeGuard : IDisposable
{
#region Construction and initialization of this instance
public static ScopeGuard WithOnLeave(Action onLeave)
{
return new ScopeGuard(onLeave);
}
private ScopeGuard(Action onLeave)
{
this.onLeave = onLeave ?? delegate { };
}
private Action onLeave;
#endregion Construction and initialization of this instance
#region Change leave action
public void OnLeave(Action onLeave)
{
this.onLeave = onLeave ?? delegate { };
}
#endregion Change leave action
#region IDisposable Member
public void Dispose()
{
var tmp = this.onLeave;
this.onLeave = null; // set to null first, tmp() could throw
tmp?.Invoke();
}
#endregion IDisposable Member
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment