Search code examples
c#.netmultithreadingreaderwriterlockslim

Is ReaderWriterLockSlim the right choice?


I'm writing a global error handler/logger for applications running in Windows Azure. When an error occurs in the application, a number of operations are performed that need to happen atomically. I need to prevent an error from being logged until the previous one has completed. Meanwhile, I want reads of the logs to occur as needed.

My initial thought was using a Monitor/lock and lock only the error writes. That way the reads aren't inhibited at all. I was wondering though whether a ReaderWriterLockSlim would be more appropriate. I can't say I truly understand the value between one approach vs. the other.

Should I create a ReaderWriterLockSlim and do something like the following below (with reads being wrapped in EnterReadLock)...

public static void LogError(Exception exception)
{
    _lock.EnterWriteLock();

    ...

    _lock.ExitWriteLock();
}

Or do I simply do something like the following, only locking the write sections:

public static void LogError(Exception exception)
{
     lock (someStaticLock)
     {
        ...
     }
}

Any thoughts/advice would be much appreciated.


Solution

  • OK, it entirely depends on how resource contention is expected. Following is a simple decision I would make based on what I'm locking and how much locking.

    ReaderWriterLockSlim is implemented using a spinlock, therefore if you have long locking resources (writing text in this case) it would lead to a worse performance because of spinning by waiting threads. That said, its very useful tool in following situations.

    • If you have a lot of locks and each of them is finer grained (locks for very small pieces of code) then ReaderWriterLockSlim or (spinlock).
    • Number of threads or contentions expected is high spinlock makes sense provided locking is fine grained.

    Lock or Monitor is best suited when your contentions are coarsegrained and you know that contentions or number of locks are lower.

    ReaderWriterLockSlim is comparatively faster than ReaderWriterLock atleast 3-5 times.