Latest Replies
Wednesday
Dec172008

How to handle .NET ReaderWriter locks efficiently?

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:

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.

« Development Compromises Around Lambda Expressions | Main | MsBuildToCCNetLogger fails on shutdown (MSB4015) »

References (1)

References allow you to track sources for this article, as well as articles that were written in response to this article.

Reader Comments (3)

Hi,

Great Article,

Here is a Singleton Pattern implemented with the ReadWriterLockSlim

ttp://blog.sb2.fr/post/2008/11/16/ThreadSafe-Singleton-et-ReaderWriterLockSlim.aspx

December 18, 2008 | Unregistered CommenterYoann. B

Nice idea Yoann.

Although I definitely prefer to let the IoC container handle the usage patterns (Singleton, Cached, Factory) along with the proper disposal, instead of manually coding this)

My favorite IoC Container for .NET is Autofac

December 18, 2008 | Registered CommenterRinat Abdullin

Thanks for the link. I did something almost exactly the same as you did. One thing you might want to look at is specifying a timeout for the locks. I had extended it so if the lock couldn't be acquired within the timeout, a timeout exception was thrown. It's nice for avoiding deadlocks...which you never think will hit you..until they do!

December 18, 2008 | Unregistered CommenterBrian C
Comments for this entry have been disabled. Additional comments may not be added to this entry at this time.