Lock/NoLock code

There was a comment that the LazyLoader was not thread safe.  We decided to add thread safety & refactor.


One of the concerns we had was that locking isn’t necessary if you know ahead of time that you’ll always be single-threaded.  You may not want to take the performance hit.


One very common coding idiom is the lock-and-create code.  We encapsulated this behavior in a new class, as well as providing a way to accept no-lock semantics:


interface ILock : IDisposable


    IDisposable Aquire();



class Lock : ILock


    readonly Mutex mutex = new Mutex(false);


    IDisposable ILock.Aquire()



        return this;



    void IDisposable.Dispose()






class NoLock : ILock


    IDisposable ILock.Aquire() { return null; }

    void IDisposable.Dispose() { }



In your code, you have an ILock instance (really a Lock or a NoLock), and then:

using (@lock.Aquire())



Comments (4)

  1. David M. Kean says:

    According to the design guidelines(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/scalenetchapt04.asp) mutexes are only supposed to be used for cross process communication, too expensive I imagine…

  2. jaybaz [MS] says:

    Hmm, yeah it does say to use ‘lock’ for this.

    I think you get:

    readonly object gate = new object();

    Aquire { Monitor.Enter (gate); }

    Dispose { Monitor.Exit (gate); }

    Does that look right?

    It’d be wise of me to look http://www.interact-sw.co.uk/iangblog/2004/03/23/locking for some ways of making this locking code safer to consume.

  3. Cyrus Najmabadi says:

    Good point David. We actually were talking about what lock actually means when we were breaking it out into it’s own type to handle locking. I find it very interesting that we were discussing how to extract lock() into it’s own object. We mentioned that:


    try {

    } finally {



    and then also mentioned we needed something like a monitor that we could Enter and Exit. What did we come up with though? A Mutex!! 🙂

    Well, here’s to the benefits that arise from peer review. Thanks very much David.