Skip to content

Instantly share code, notes, and snippets.

@cammerman
Created July 27, 2011 19:15
Show Gist options
  • Save cammerman/1110134 to your computer and use it in GitHub Desktop.
Save cammerman/1110134 to your computer and use it in GitHub Desktop.
Idea for a double-checked lock helper object.
// Latch definition
public class DoubleCheckLockLatch
{
private readonly Object _lockSync = new Object();
private readonly Func<bool> _isLatchClosed;
public DoubleCheckLockLatch(Func<bool> isLatchClosed)
{
_isLatchClosed = isLatchClosed;
}
public virtual bool Latch(Action latchedAction)
{
var latchWasClosed = false;
if (_isLatchClosed())
{
lock (_lockSync)
{
if (_isLatchClosed())
{
latchedAction();
}
else
{
latchWasClosed = true;
}
}
}
else
{
latchWasClosed = true;
}
return latchWasClosed;
}
}
// Usage
public class UseLatch
{
private readonly ILog _log;
private readonly DoubleCheckLockLatch _latch;
private bool _running = false;
public UseLatch(ILog log)
{
_log = log;
_latch = new DoubleCheckLockLatch(() => _running);
}
public void ReEntrant()
{
if (_latch.Latch(() => this.DoWork()))
{
Log("Attempted to restart work while already in progress.");
}
}
private void DoWork()
{
_running = true;
// Do the work.
_running = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment