我知道不建议将其用于锁,因为可以在难以控制的类之外修改对象。因此,始终建议使用私有字段进行锁定。(我看过:为什么 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)
}
}
}
}