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

后端 未结 6 1099
长情又很酷
长情又很酷 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:17

    Your lock will be released properly. A lock acts like this:

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

    And finally blocks are guaranteed to execute, no matter how you leave the try block.

提交回复
热议问题