12

i have a question .. is it ok if i have something like this :

try 
{ 
    lock(programLock) 
    {
         //some stuff 1
    }
}
catch(Exception ex) { //stuff 2 }

i am curious if "some stuff 1" causes an exception , does programLock still remains locked ?

Emond
  • 49,011
  • 11
  • 81
  • 108
Alex
  • 10,329
  • 28
  • 89
  • 163

5 Answers5

15

No, the lock will be released, lock is roughly equivalent to this:

try
{
    Monitor.Enter(programLock);
    // some stuff 1
}
finally
{
    Monitor.Exit(programLock);
}

(Meaning if an exception is thrown, Monitor.Exit will get called automatically as you exit the scope of the lock statement)

Kieren Johnstone
  • 40,197
  • 14
  • 86
  • 141
6

Lock() is nothing but

try
{
   Monitor.Enter(...);
}
finally
{
   Monitor.Exit(....);
}

So it already takes care of it.

Aliostad
  • 78,844
  • 21
  • 155
  • 205
4

From msdn documentation

"... lock or SyncLock insures that the underlying monitor is released, even if the protected code throws an exception."

note: You can create your own exception safe blocks for arbitrary actions with using blocks, .net's version of the RAII idiom.

Krypes
  • 561
  • 2
  • 10
2

No. leaving the lock braces will always unlock.

Emond
  • 49,011
  • 11
  • 81
  • 108
2

No, it will not remain locked.

The "closing brace" of the lock is basically the finally clause of the Monitor.Exit.

See this associated StackOverflow Question.

Does a locked object stay locked if an exception occurs inside it?

Community
  • 1
  • 1
Tim P.
  • 2,853
  • 23
  • 26