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

后端 未结 6 1103
长情又很酷
长情又很酷 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条回答
  •  旧时难觅i
    2020-11-27 03:21

    yes, that will release properly; lock acts as try/finally, with the Monitor.Exit(myLock) in the finally, so no matter how you exit it will be released. As a side-note, catch(... e) {throw e;} is best avoided, as that damages the stack-trace on e; it is better not to catch it at all, or alternatively: use throw; rather than throw e; which does a re-throw.

    If you really want to know, a lock in C#4 / .NET 4 is:

    {
        bool haveLock = false;
        try {
           Monitor.Enter(myLock, ref haveLock);
        } finally {
           if(haveLock) Monitor.Exit(myLock);
        }
    } 
    

提交回复
热议问题