Picking Locks

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...

Tags:

C#

Comments are closed

Kofi Sarfo modified theme by Mads Kristensen



Content by WIMIRO Technology is licensed under a Creative Commons Attribution-Share Alike 2.0 UK: England & Wales License.

Creative Commons License

Powered by BlogEngine.NET 1.5.0.7

About Me

Director, Wimiro Technology
London, United Kingdom

Writes in third person and first person plural; currently commutes to Moorgate.

Kiva Loans

  • Issa Sarr

    Issa Sarr

    Personal Purchases

    Requested loan: $200

    Amount raised: $75

    Dakar, Senegal

    social needs

    Loan Now »

  • Edwin

    Edwin

    Movie Tapes & DVDs

    Requested loan: $800

    Amount raised: $125

    La Paz, Bolivia

    Buy a DVD burner tower

    Loan Now »

  • Soo

    Soo

    Laundry

    Requested loan: $5375

    Amount raised: $2175

    Queens, New York, United States

    To purchase a new dry cleaning machine

    Loan Now »

 To see more entrepreneurs »

Kiva Loans