.NET ReaderWriterLockSlim issues

.net, multithreading, thread-safety

Solution

The upside of using `EnterUpgradeableReadLock` over `EnterReadLock` is that you can know for sure that the condition that you check in order to determine whether to enter the write lock or not does not change between checking the condition and actually entering the write lock. This avoids the duplication that may be needed with regular `lock`s:

if (whatever-condition)
{
    lock (_lockObject)
    {
        // the condition may have changed betwen the check and the lock; verify
        // that the condition is still valid
        if (whatever-condition)
        {
            // do the stuff
        }
    }
}

At the same time, it does not block calls to `EnterReadLock`, so other threads may still get read access in other parts of the code (and those calls will, of course, block the call to `EnterWriteLock` until they release the read locks).

Problem

There are lots written about the ReaderWriterLockSlim class which allows multiple read and a single write. All of these (at least that I had found) tell how to use it without much explanation why and how it works. The standard code sample is: ``` lock.EnterUpgradeableReadLock(); try { if (test if write is required) { lock.EnterWriteLock(); try { change the resourse here. } finally { lock.ExitWriteLock(); } } } finally { lock.ExitUpgradeableReadLock(); } ``` The question is: if upgradeable lock permits only a single thread to enter its section, why I should call EnterWriteLock method within? What will happen if I don't? Or what will happen if instead of EnterUpgradeableReadLock I will call EnterWriteLock and will write to a resource without using upgradeable lock at all?

Original source