如果锁定的对象内部发生异常,它会保持锁定状态吗?

Does a locked object stay locked if an exception occurs inside it?(如果锁定的对象内部发生异常,它会保持锁定状态吗?)
本文介绍了如果锁定的对象内部发生异常,它会保持锁定状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 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.

这篇关于如果锁定的对象内部发生异常,它会保持锁定状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?(Linq to SQL 中是否提供 Unpivot(非 Pivot)功能?如何?)
How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Linq2SQl eager load with multiple DataLoadOptions(具有多个 DataLoadOptions 的 Linq2SQl 急切加载)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)