Writing code for the concurrent execution requires, among over things, proper data access synchronization (locking) to avoid any problems. One of the most useful primitives to do that is the Slim version of ReaderWriterLock that has been introduced in .NET 3.5

ReaderWriterLockSlim represents a lock that is used to manage access to a resource, allowing multiple threads for reading or exclusive access for writing.

Advantages of this lock over the previous version of ReaderWriterLock include:

  • Performance is much better (see post at valerio.net for details).
  • In the scenarios, when reads are more frequent than writes, we will get better performance, compared to the raw Monitor usage.
  • Slim lock allows to have designs that are cleaner of lock recursion.
  • Provides upgrades that are deadlock-free and atomic.

Extensions class for ReaderWriterLockSlim in Lokad Shared Libraries allows you to handle this new lock in a more efficient maner.

For example, instead of this C# code:

_lock.GetUpgradeableReadLock();
try
{
  if (_queue.Count > 0)
  {
    _lock.GetWriteLock();
    try
    {
      value = _queue.Dequeue();
      return true;
    }
    finally
    {
      _lock.ExitWriteLock();
    }
  }
}
finally
{
  _lock.ExitUpgradeableReadLock();
}

you can simply write this:

using (_lock.GetUpgradeableReadLock())
{
  if (_queue.Count > 0)
  {
    using (_lock.GetWriteLock())
    {
      value = _queue.Dequeue();
      return true;
    }
  }
}

This extension is available to you as long as you are using System.Threading namespace and have Lokad.Shared.dll referenced.

Posted in C#