gpt4 book ai didi

c# - 锁定字段或局部变量?

转载 作者:太空狗 更新时间:2023-10-29 17:36:55 29 4
gpt4 key购买 nike

在我阅读 this 之后用an answer提问来自马克....

我有时会看到人们锁定一个本地变量。

这段代码有问题吗?

public void Do()
{
object o = new Object();
lock (o)
{
...
}
}

我相信object o = new Object();应该作为 Field 在方法之外 .

因为每个线程都得到一个新的 o 实例,会有多个锁。

我在这里错过了什么?在这种特定情况下,它不应该锁定字段吗?

最佳答案

I believe object o = new Object(); should be outside the method as a Field.

Since each thread is getting a new instance of o, there will bemultiple locks.

What am I missing here? Shouldn't it lock on fields in this specific case?

你的理解是正确的。密码坏了。在此实现中,即使锁定将处于事件状态,它也不会提供同步,因为它位于不同的对象上。

来自 Microsoft Docs

When you synchronize thread access to a shared resource, lock on adedicated object instance (for example, private readonly objectbalanceLock = new object();) or another instance that is unlikely tobe used as a lock object by unrelated parts of the code. Avoid usingthe same lock object instance for different shared resources, as itmight result in deadlock or lock contention. In particular, avoidusing the following as lock objects:

this, as it might be used by the callers as a lock. Type instances, asthose might be obtained by the typeof operator or reflection. stringinstances, including string literals, as those might be interned. Holda lock for as short time as possible to reduce lock contention.

关于c# - 锁定字段或局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14193231/

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