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