Created
July 27, 2011 19:15
-
-
Save cammerman/1110134 to your computer and use it in GitHub Desktop.
Idea for a double-checked lock helper object.
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
// 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