Umbraco – WriteLock and ReadLock with ReaderWriterLockSlim

this post is to clear how to use WriteLock and ReadLock to make sure critical resources have been visited properly.

Take the following code for example in “public abstract class ResolverBase : ResolverBase where TResolver : ResolverBase”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public static TResolver Current
{
  get
    {
      using (new ReadLock(ResolversLock))
        {
          if (_resolver == null)
            throw new InvalidOperationException(string.Format("Current has not been initialized on {0}. You must initialize Current before trying to read it.",
                                                              typeof(TResolver).FullName));
          return _resolver;
        }
    }
 
  set
    {
      using (Resolution.Configuration)
        using (new WriteLock(ResolversLock))
        {
          if (value == null)
            throw new ArgumentNullException("value");
          if (_resolver != null)
            throw new InvalidOperationException(string.Format("Current has already been initialized on {0}. It is not possible to re-initialize Current once it has been initialized.",
                                                              typeof(TResolver).FullName));
          _resolver = value;
        }
    }
}

//The lock for the singleton.
static readonly ReaderWriterLockSlim ResolversLock = new ReaderWriterLockSlim();
“new WriteLock(ResolversLock)” is called, “ResolversLock” will be referenced by _rwLock. WriteLock constructor will enter lock automatically by “_rwLock.EnterWriteLock();”

when it disposed by calling IDisposable.Dispose(), invoking “_rwLock.ExitWriteLock();” to exit WriteLock.

“new ReadLock(ResolversLock)” is called, “ResolversLock” will be referenced by _rwLock. ReadLock constructor will enter lock automatically and exit readlock when disposed.

This entry was posted in Umbraco. Bookmark the permalink.