Lock/NoLock code

Published 06 May 04 02:51 PM

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()

    {

        this.mutex.WaitOne();

        return this;

    }

 

    void IDisposable.Dispose()

    {

        this.mutex.ReleaseMutex();

    }

}

 

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

# David M. Kean said on May 6, 2004 3:58 PM:
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...
# jaybaz [MS] said on May 6, 2004 4:49 PM:
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.
# jaybaz_MS's WebLog said on May 7, 2004 7:04 PM:
# Cyrus Najmabadi said on May 7, 2004 4:22 PM:
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:

Monitor.Enter(this)
try {
...
} finally {
Monitor.Exit(this);
}

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.
New Comments to this post are disabled

This Blog

Syndication

Page view tracker