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

后端 未结 6 1091
长情又很酷
长情又很酷 2020-11-27 02:39

In a c# threading app, if I were to lock an object, let us say a queue, and if an exception occurs, will the object stay locked? Here is the pseudo-code:

in         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 03:08

    Just to add a little to Marc's excellent answer.

    Situations like this are the very reason for the existence of the lock keyword. It helps developers make sure the lock is released in the finally block.

    If you're forced to use Monitor.Enter/Exit e.g. to support a timeout, you must make sure to place the call to Monitor.Exit in the finally block to ensure proper release of the lock in case of an exception.

提交回复
热议问题