Search code examples
c#.netmultithreadingreaderwriterlockslim

ReaderWriterLockSlim and timer


I have a frustration with ReaderWriterLockSlim and delaying ExitWriteLock. Why is the WriteLock released in timers callback?

var _lock = new ReaderWriterLockSlim();
_lock.EnterWriteLock();
Assert.AreEqual(true, _lock.IsWriteLockHeld);   // good

System.Threading.Timer timer = new Timer(state =>
{
    _lock.ExitWriteLock(); //throws exception that lock is not held
}, null, 1, -1);

Thread.Sleep(1000);
Assert.AreEqual(false, _lock.IsWriteLockHeld);

Solution

  • By the looks of the constructor, you're using a System.Threading.Timer. The callback of that timer runs on a threadpool thread.

    The write lock isn't released, it's just that the callback you specified for the Timer runs on a different thread, and that thread doesn't hold the write lock, so the assertion Assert.AreEqual(true, _lock.IsWriteLockHeld); in the callback fails, causing an exception.

    One thread enters a lock, and only for that thread does IsWriteLockHeld hold true, and only that thread can exit the lock.