tags:

views:

299

answers:

1
+1  Q: 

Read locks in .net

In any DBMS that's more than half-baked, there is a distinction between a read lock and an update lock. In my multi-threaded C# code, I have, to date, used the lock keyword, but today it came to me that performance in my application would be a lot better if I could make this read vs write distinction in locking; I have many threads that could safely read at the same time, but they obstruct each other for the sake of the infrequent but inevitable writes.

I could, and I suppose I will have to, implement my own locking scheme in which the request for a write-lock both stalls the acquisition of further read locks and is stalled until the extant read locks are released.

None of this is profoundly difficult, and all of it is described in stupefying detail by Date and others in any database theory text you care to name.

Surely I'm not the first to face this need? What's out there, particularly for C#?


Thank you, Dmitri.

The other thing I hoped for was any experiences and comments people might have on the strengths and weaknesses of any libraries you may have tried.

Good heavens, that's in System.Core! Stop it, Dmitri, you're making me feel old.

I wonder what's the most practical way to lobby Microsoft to provide syntactical sugar similar to the lock (object) { ... } syntax.

Adapted from the MSDN sample

public class SynchronizedCache
{
  private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
  private Dictionary<int, string> innerCache = new Dictionary<int, string>();

  public string Read(int key)
  {
    cacheLock.EnterReadLock();
    try
    {
      return innerCache[key];
    }
    finally
    {
      cacheLock.ExitReadLock();
    }
  }

  public void Add(int key, string value)
  {
    cacheLock.EnterWriteLock();
    try
    {
      innerCache.Add(key, value);
    }
    finally
    {
      cacheLock.ExitWriteLock();
    }
  }
...

which closely parallels explicit use of Monitor. With a little help from MS it could be as clean and simple as this.

private Dictionary<int, string> innerCache = new Dictionary<int, string>();

public string Read(int key)
{
  readlock(innerCache) return innerCache[key];
}
public void Add(int key, string value)
{
  writelock (innerCache) innerCache.Add(key, value);
}
+4  A: 

Take a look at ReaderWriterLockSlim class (or its older version, ReaderWriterLock). This lock class distinguishes between read and write locks, allowing you to have multiple readers but only a single writer.

Dmitri Nesteruk