请问,如果里面出现异常锁定的对象保持锁定状态?异常、里面、对象、状态

2023-09-02 20:43:42 作者:荒凉的午夜

在C#中的线程应用程序,如果我要锁定对象,我们可以说一个队列,如果出现异常,将对象保持锁定状态?这里是伪code:

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:

int ii;
lock(MyQueue)
{
   MyClass LclClass = (MyClass)MyQueue.Dequeue();
   try
   {
      ii = int.parse(LclClass.SomeString);
   }
   catch
   {
     MessageBox.Show("Error parsing string");
   }
}

据我了解,code后抓不执行 - 但我一直在想,如果锁将被释放。

As I understand it, code after the catch doesn't execute - but I have been wondering if the lock will be freed.

推荐答案

第一;你有没有考虑的TryParse?

First; have you considered TryParse?

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

锁将被释放2个原因;首先,锁定基本上是:

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.

 
精彩推荐