ReaderWriterLockSlim and Pulse/Wait

Posted by Jono on Stack Overflow See other posts from Stack Overflow or by Jono
Published on 2010-04-22T14:31:01Z Indexed on 2010/04/22 14:33 UTC
Read the original article Hit count: 262

Filed under:
|
|

Is there an equivalent of Monitor.Pulse and Monitor.Wait that I can use in conjunction with a ReaderWriterLockSlim?

I have a class where I've encapsulated multi-threaded access to an underlying queue. To enqueue something, I acquire a lock that protects the underlying queue (and a couple of other objects) then add the item and Monitor.Pulse the locked object to signal that something was added to the queue.

public void Enqueue(ITask task)
{
    lock (mutex)
    {
        underlying.Enqueue(task);
        Monitor.Pulse(mutex);
    }
}

On the other end of the queue, I have a single background thread that continuously processes messages as they arrive on the queue. It uses Monitor.Wait when there are no items in the queue, to avoid unnecessary polling. (I consider this to be good design, but any flames (within reason) are welcome if they help me learn otherwise.)

private void DequeueForProcessing(object state)
{
    while (true)
    {
        ITask task;
        lock (mutex)
        {
            while (underlying.Count == 0)
            {
                Monitor.Wait(mutex);
            }
            task = underlying.Dequeue();
        }
        Process(task);
    }
}

As more operations are added to this class (requiring read-only access to the lock protected underlying), someone suggested using ReaderWriterLockSlim. I've never used the class before, and assuming it can offer some performance benefit, I'm not against it, but only if I can keep the Pulse/Wait design.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about c#