by Kofi Sarfo
18. September 2009 18:35
One fact I forget with consistent regularity is that locks in C# and .NET for that matter are implemented using the System.Threading.Monitor class.
static object moveCountLock = new Object();
private int moveCount;
private void IncrementMoveCount()
{
Monitor.Enter(moveCountLock);
moveCount++;
Monitor.Exit(moveCountLock);
}
And if we were to place the Monitor.Exit in a Finally part of the Try/Catch then effectively it becomes the following:
private void IncrementMoveCount()
{
lock (moveCountLock)
{
moveCount++;
}
}
To put this all in some context, the code above is designed to address race conditions though the MSDN article on Concurrency from which I take this summary elaborates on locks. And whilst we're discussing locks it's worth considering the volatile keyword.
For non-volatile fields, optimization techniques that reorder instructions can lead to unexpected and unpredictable results in multi-threaded programs that access fields without synchronization such as that provided by the lock-statement.
Two things worth pointing out here. It turns out the famous Double-Check Locking flaw previously requiring the volatile keyword no longer needs one. At least not if you're using C# but might as well leave it in for Mono and friends, suggests Phil Haack in: Double Check Locking and Other Premature Optimizations Can Shoot You In The Foot.
A few hours worth of reading ahead I think...