gpt4 book ai didi

.Net4, Monitor.Enter(lockObject, acquiredLock)

转载 作者:行者123 更新时间:2023-12-01 12:00:59 25 4
gpt4 key购买 nike

在 .Net4 中,Monitor.Enter(Object)被标记为过时:

[ObsoleteAttribute("This method does not allow its caller to reliably release the lock.  Please use an overload with a lockTaken argument instead.")]
public static void Enter(
Object obj
)

还有一个新方法Monitor.Enter(lockObject, acquiredLock)使用这种用法:

bool acquiredLock = false;

try
{
Monitor.Enter(lockObject, ref acquiredLock);

// Code that accesses resources that are protected by the lock.

}
finally
{
if (acquiredLock)
{
Monitor.Exit(lockObject);
}
}

我以前是这样做的:

Monitor.Enter(lockObject);
try
{

// Code that accesses resources that are protected by the lock.
}
finally
{
Monitor.Exit(lockObject);
}

错了吗?为什么 ?也许在输入之后但在尝试之前有一个中断?
正如 Eamon Nerbonne 所问:如果在 monitor.exit 之前的 finally 中出现异步异常会怎样?

答案:ThreadAbortException

When this exception is raised, the runtime executes all the finally blocks before ending the thread.

最佳答案

正如您在问题末尾所建议的那样,问题是 asynchronous exception可以在调用 Monitor.Enter 之后但在您输入 try block 之前抛出。

新的处理方式确保无论发生什么情况,您都将到达 finally block 并能够释放锁定如果您获得了它。 (例如,如果 Monitor.Enter 抛出异常,您可能无法获取它。)

IIRC,这是针对 .NET 4.0 时 lock 关键字的新行为。

关于.Net4, Monitor.Enter(lockObject, acquiredLock),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1612325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com