开发者

try and lock question

开发者 https://www.devze.com 2023-02-23 01:25 出处:网络
i have a question .. is开发者_C百科 it ok if i have something like this : try { lock(programLock)

i have a question .. is开发者_C百科 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 ?


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)


Lock() is nothing but

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

So it already takes care of it.


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.


No. leaving the lock braces will always unlock.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消