gpt4 book ai didi

c# - Monitor.Enter(object, ref bool) 比 Monitor.Enter(object) 有什么优势?

转载 作者:太空狗 更新时间:2023-10-29 23:01:23 28 4
gpt4 key购买 nike

根据语言规范,lock(obj) statement; 会被编译为:

object lockObj = obj; // (the langspec doesn't mention this var, but it wouldn't be safe without it)
Monitor.Enter(lockObj);
try
{
statement;
}
finally
{
Monitor.Exit(lockObj);
}

然而,它被编译为:

try
{
object lockObj = obj;
bool lockTaken = false;
Monitor.Enter(lockObj, ref lockTaken);
statement;
}
finally
{
if (lockTaken) Monitor.Exit(lockObj);
}

这似乎比必要的要复杂得多。那么问题是,该实现的优势是什么?

最佳答案

一如既往,Eric Lippert 已经回答了这个问题:

Fabulous Adventures In Coding: Locks and exceptions do not mix

关于c# - Monitor.Enter(object, ref bool) 比 Monitor.Enter(object) 有什么优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10935092/

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