ReaderWriterLockSlim question.

Posted by Kamarey on Stack Overflow See other posts from Stack Overflow or by Kamarey
Published on 2010-03-22T16:49:33Z Indexed on 2010/03/22 16:51 UTC
Read the original article Hit count: 219

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?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about multithreading