問題描述
在 c# 線程應用程序中,如果我要鎖定一個對象,假設是一個隊列,如果發生異常,該對象會保持鎖定狀態嗎?偽代碼如下:
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");
}
}
據我了解,catch 之后的代碼不會執行 - 但我一直想知道鎖是否會被釋放.
As I understand it, code after the catch doesn't execute - but I have been wondering if the lock will be freed.
推薦答案
First;你考慮過 TryParse 嗎?
First; have you considered TryParse?
in li;
if(int.TryParse(LclClass.SomeString, out li)) {
// li is now assigned
} else {
// input string is dodgy
}
鎖會被釋放有兩個原因;首先,lock
本質上是:
The lock will be released for 2 reasons; first, lock
is essentially:
Monitor.Enter(lockObj);
try {
// ...
} finally {
Monitor.Exit(lockObj);
}
第二;您捕獲并且不重新拋出內部異常,因此 lock
實際上永遠不會看到異常.當然,您在 MessageBox 的持續時間內持有鎖,這可能是個問題.
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.
這篇關于如果鎖定的對象內部發生異常,它會保持鎖定狀態嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!