将锁移动到 Parent
类的天真的解决方案具有不同的行为:我将无法调用 new Child1().Method1()
和 new Child2().Method1()
同时进行。
有什么方法可以重构下面的代码吗?
abstract class Parent
{
protected abstract Method1();
}
class Child1 : Parent
{
static object staticLock = new object();
public void Method1()
{
lock(staticLock)
{
// Do something ...
}
}
}
class Child2 : Parent
{
static object staticLock = new object();
public void Method1()
{
lock(staticLock)
{
// Do something else ...
}
}
}
我问这个是因为它不仅仅是 2 个子类,所以真正的问题更大。
最佳答案
让每个提供锁定策略的子类实现一个方法,并将 Method1 移动到基类,如您的 other问题。
class Parent
{
public void Method1()
{
using(acquireLock())
{
Method1Impl();
}
}
protected abstract IDisposable acquireLock();
protected abstract void Method1Impl();
}
class Child : Parent
{
protected override IDisposable acquireLock()
{
// return some class that does appropriate locking
// and in Dispose releases the lock.
// may even be no-op locking.
}
}
关于c# - 如何重构这些锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9198604/