次の方法で共有


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

    {

        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

  • Anonymous
    May 06, 2004
    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...
  • Anonymous
    May 06, 2004
    The comment has been removed
  • Anonymous
    May 07, 2004
    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.