ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ReaderWriterLockSlim

Simplified and elegant usage of ReaderWriterLockSlim that

Source

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

}

Author: Sharp IT, Maciej Rychter

Submitted on: 1 jan. 2016

Language: C#

Type: System.Threading.ReaderWriterLockSlim

Views: 3381