1

A lot of examples for the ReaderWriterLockSlim are written this way:

public string Read(int key)
{
    cacheLock.EnterReadLock(); // is there a reason for this 
    try
    {
        return innerCache[key];
    }
    finally
    {
        cacheLock.ExitReadLock();
    }
}

Is there a real reason for the EnterLock to be outside the try block ?

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
xdroid81
  • 11
  • 2
  • 3
    If it is inside the try block then it would be a bug. If EnterReadLock fails with an exception then the finally block will bomb as well since the lock isn't held. An exception in finally block code is very, very bad since it replaces the active exception. – Hans Passant Dec 12 '18 at 10:25
  • So the only reason is to avoid that an exception in finally will replace the active exception in case the enter lock fails. ok, thx! – xdroid81 Dec 12 '18 at 10:50

0 Answers0