Search code examples
c#.netvb.netparallel-processingreaderwriterlock

How would you simplify Entering and Exiting a ReaderWriterLock?


This seems very noisy to me. Five lines of overhead is just too much.

m_Lock.EnterReadLock()
Try
    Return m_List.Count
Finally
    m_Lock.ExitReadLock()
End Try

So how would you simply this?


Solution

  • I was thinking the same, but in C# ;-p

    using System;
    using System.Threading;
    
    class Program
    {
        static void Main()
        {
            ReaderWriterLockSlim sync = new ReaderWriterLockSlim();
    
            using (sync.Read())
            {
               // etc    
            }
        }
    
    
    }
    public static class ReaderWriterExt
    {
        sealed class ReadLockToken : IDisposable
        {
            private ReaderWriterLockSlim sync;
            public ReadLockToken(ReaderWriterLockSlim sync)
            {
                this.sync = sync;
                sync.EnterReadLock();
            }
            public void Dispose()
            {
                if (sync != null)
                {
                    sync.ExitReadLock();
                    sync = null;
                }
            }
        }
        public static IDisposable Read(this ReaderWriterLockSlim obj)
        {
            return new ReadLockToken(obj);
        }
    }