2

我知道不建议将其用于锁,因为可以在难以控制的类之外修改对象。因此,始终建议使用私有字段进行锁定。(我看过:为什么 lock(this) {...} 不好?

受保护的锁呢?我认为我应该做得很好,因为我的课程是内部的,没有人可以在我的装配之外从它们中派生出来......

请注意,我不能使用单独的派生锁和基类锁,因为在多个类中难以管理可能会发生死锁。

internal class Base
{
    protected object sync = new object();
    public string Foo
    {
        get
        {
            lock (sync)
            {
                //set it
            }
        }
    }
}

internal class Derived : Base
{
    public string Bar
    {
        get
        {
            lock (sync)
            {
                //set it
                //try to  get "Foo" (if i use seperate locks-syncobjects
                // in derived and base class there can be a ptoential deadlock)
            }
        }
    }
}
4

1 回答 1

0

您应该为每个字段使用锁定对象,我认为它会解决您的问题。

我想用同一个锁对象锁定对所有字段的访问,我建议你在基类中实现锁机制

protected 可能会导致与 public 相同的问题,因为您不知道谁将从您的类继承。例如,如果在获取某个值时您想使用基类中的某个其他字段,那么您将失败。

所以 - 保护也不好

于 2013-06-03T05:26:23.077 回答