Skip to content

Instantly share code, notes, and snippets.

@AnthonyMastrean
Created September 6, 2012 14:55
Show Gist options
  • Save AnthonyMastrean/3657058 to your computer and use it in GitHub Desktop.
Save AnthonyMastrean/3657058 to your computer and use it in GitHub Desktop.
Latch object and some related behavior
namespace System
{
public class Latch
{
public static explicit operator Latch(bool isSet)
{
return new Latch(isSet);
}
public static implicit operator bool(Latch latch)
{
return latch._isSet;
}
private bool _isSet;
public Latch(bool isSet = false)
{
_isSet = isSet;
}
public void Set()
{
_isSet = true;
}
public void Clear()
{
_isSet = false;
}
public override string ToString()
{
return _isSet.ToString();
}
public IDisposable SetTemporarily()
{
Set();
return new DisposableAction(Clear);
}
}
}
public class SomeGuardingActor
{
private readonly Latch _open = new Latch();
// This structure is a common usage of the Latch, a gaurd clause and
// a matching Set. It would be nice to have a safer syntax, like
//
// using(_open.GaurdThenSet()) { ... }
//
public void Open()
{
if(_open)
return;
// ... open ...
_open.Set();
}
public void Close()
{
if(!_open)
return;
// ... close ...
_open.Clear();
}
}
public class SomeTemporaryActor.cs
{
private readonly Latch _editable = new Latch();
private void OnSomeValueModified(object sender, EventArgs e)
{
if(!_editable)
return;
// ... track changes ...
}
public void Modify(string value)
{
using(_editable.SetTemporarily())
{
SomeValue = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment