ReaderWriterLockSlim gets stuck on TryEnterReadLock

716 Views Asked by At

I have following code:

    private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();

    private void TryGetReadLock()
    {
        if (!Locker.IsWriteLockHeld && !Locker.IsReadLockHeld)
            Locker.TryEnterReadLock(WaitTimeout);
    }

Locker.TryEnterReadLock times out. If I stop the debugger before it times out, both Locker.IsWriteLockHeld and Locker.IsReadLockHeld are false.

Question: why would TryEnterReadLock wait in this particular case?

[EDIT] Indeed, as indicated in the comments I have lock between checking your if condition and entering the if block. So, I have tried to remove the if and leave just Locker.TryEnterReadLock(WaitTimeout);, but I receive the following error:

Additional information: A read lock may not be acquired with the write lock held in this mode.

Indeed some other thread has a write lock (Locker.IsWriteLockHeld = true).

What I want is obtain classic lock locking when one thread has the write lock, that is have the threads wait until one it finishes, but I cannot find a way to do it.

0

There are 0 best solutions below