Skip to content

Instantly share code, notes, and snippets.

@kostrse
Last active February 27, 2016 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kostrse/b8913471ee6e64488bb1 to your computer and use it in GitHub Desktop.
Save kostrse/b8913471ee6e64488bb1 to your computer and use it in GitHub Desktop.
public class StateSwitch
{
private readonly Action enterAction;
private readonly Action leaveAction;
private readonly bool leaveOnSuspend;
private uint counter;
private bool entered;
private bool suspended;
public StateSwitch(Action enterAction, Action leaveAction, bool leaveOnSuspend = false)
{
this.enterAction = enterAction;
this.leaveAction = leaveAction;
this.leaveOnSuspend = leaveOnSuspend;
}
public void Enter()
{
if (this.counter++ == 0 && !this.suspended)
{
this.DoEnter();
}
}
public void Leave()
{
if (this.counter == 0)
{
throw new InvalidOperationException("Unable to leave state more times than it was entered.");
}
if (--this.counter == 0 && !this.suspended)
{
this.DoLeave();
}
}
public void Suspend()
{
if (this.suspended)
{
return;
}
if (this.leaveOnSuspend && this.entered)
{
this.DoLeave();
}
this.suspended = true;
}
public void Resume()
{
if (!this.suspended)
{
return;
}
this.suspended = false;
if (this.counter == 0 && this.entered)
{
this.DoLeave();
}
else if (this.counter > 0 && !this.entered)
{
this.DoEnter();
}
}
private void DoEnter()
{
this.entered = true;
this.enterAction();
}
private void DoLeave()
{
this.entered = false;
this.leaveAction();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment