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
  • 50,210
  • 11
  • 84
  • 115
Alex
  • 10,869
  • 28
  • 93
  • 165

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
  • 41,277
  • 16
  • 94
  • 144
6

Lock() is nothing but

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

So it already takes care of it.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
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
  • 50,210
  • 11
  • 84
  • 115
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,903
  • 24
  • 26