Created
September 6, 2012 14:55
-
-
Save AnthonyMastrean/3657058 to your computer and use it in GitHub Desktop.
Latch object and some related behavior
This file contains 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
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); | |
} | |
} | |
} |
This file contains 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 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(); | |
} | |
} |
This file contains 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 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