c# - Lock 语句 - 它总是释放锁吗?

标签 c# .net multithreading

我最近读了this post from Eric Lippert regarding the lock implementation in c#仍然存在一些问题。

在 4.0 实现中,如果在执行 finally block 中的 Monitor.Exit(temp) 之前发生线程中止或任何跨线程异常 - 是否会保持对对象的锁定?

是否有可能在此级别发生异常,使对象仍处于锁定状态?

最佳答案

In 4.0 implementation if a thread abort or any cross thread exception occurs just before the Monitor.Exit(temp) in the finally block is executed - would that keep the lock on the object?

让我们看一下该代码,以便其他读者清楚:

bool lockWasTaken = false;
var temp = obj;
try 
{ 
  Monitor.Enter(temp, ref lockWasTaken); 
  { 
    body 
  } 
}
finally 
{ 
  if (lockWasTaken) 
  {
    // What if a thread abort happens right here?
    Monitor.Exit(temp); 
  }
}

您的问题无法回答,因为它基于一个错误的假设,即线程中止可能发生在 finally block 的中间。

线程中止不能发生在 finally block 的中间。这只是您永远不应该尝试中止线程的众多原因之一。整个线程可以在 finally block 中运行,因此是不可中止的。

Is there any possibility for an exception to occur at this level, leaving the object still in a locked state?

没有。线程中止将被延迟,直到控制离开 finally。解锁有效锁不会分配内存或引发其他异常。

关于c# - Lock 语句 - 它总是释放锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19225876/

相关文章:

c# - 加入用户控件的两个字符串属性(firstName + lastName)并将其分配给标签

python - 通过使用多进程和多线程的 asyncio 提高 "Sending 100,000 request"的速度

C# XmlSerializer 修剪空格

c# - OpenXML 如何添加指向另一个工作表的超链接

c# - .NET Core 中的 *deps.json 文件

c# - 将日志文件的日期转换为字符串,然后将数据库的字符串转换为日期时间

c# - WPF-在第一个组合框选择上启用第二个组合框

python - joblib 中的 batch_size 和 pre_dispatch 到底是什么意思

linux - 在这种情况下,我应该在单独的线程中读取文件吗?

c# - Soap服务方法类定义c#