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

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

    First; have you considered TryParse?

    in li;
    if(int.TryParse(LclClass.SomeString, out li)) {
        // li is now assigned
    } else {
        // input string is dodgy
    }
    

    The lock will be released for 2 reasons; first, lock is essentially:

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

    Second; you catch and don't re-throw the inner exception, so the lock never actually sees an exception. Of course, you are holding the lock for the duration of a MessageBox, which might be a problem.

    So it will be released in all but the most fatal catastrophic unrecoverable exceptions.

提交回复
热议问题