请问,如果里面出现异常锁定的对象保持锁定状态? [英] Does a locked object stay locked if an exception occurs inside it?
问题描述
在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.
这篇关于请问,如果里面出现异常锁定的对象保持锁定状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!