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

  • Stalamarice Nthomo Kangi

    Stalamarice Nthomo Kangi

    Tailoring

    Requested loan: $375

    Amount raised: $0

    Machakos, Kenya

    To buy fabric

    Loan Now »

  • Jonathan Mututu Kasyoka

    Jonathan Mututu Kasyoka

    Internet Cafe

    Requested loan: $500

    Amount raised: $0

    Machakos, Kenya

    To buy more chairs, tables and printer paper

    Loan Now »

  • Jeanciana Rin

    Jeanciana Rin

    General Store

    Requested loan: $300

    Amount raised: $0

    Katutungan, Wao Lanao Del Sur, Philippines

    To purchase additional inventory and to use as working capital

    Loan Now »

 To see more entrepreneurs »

Kiva Loans