ReaderWriterLockSlim

public static class ThreadingExtensions
    {
        public static void Write(this ReaderWriterLockSlim rwlock, Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            rwlock.EnterWriteLock();

            try
            {
                action();
            }
            finally
            {
                rwlock.ExitWriteLock();
            }
        }

        public static void Read(this ReaderWriterLockSlim rwlock, Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            rwlock.EnterReadLock();

            try
            {
                action();
            }
            finally
            {
                rwlock.ExitReadLock();
            }
        }

        public static void ReadUpgradable(this ReaderWriterLockSlim rwlock, Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            rwlock.EnterUpgradeableReadLock();

            try
            {
                action();
            }
            finally
            {
                rwlock.ExitUpgradeableReadLock();
            }
        }
    }
Example:
[Test]
        public void ThreadExtensions()
        {
            var cacheLock = new ReaderWriterLockSlim();
            var innerCache = new Dictionary<int, string>();

            var value = "value1";
            var readvalue = string.Empty;

            cacheLock.Write(() => innerCache[1] = value);
            cacheLock.Read(() => readvalue = innerCache[1]);

            Assert.AreEqual(value, readvalue);

        }

Description

Simplified and elegant usage of ReaderWriterLockSlim that

Details

Double click on the code to select all.

 

;