Last active
January 23, 2017 06:48
-
-
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)
This file contains hidden or 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
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