The naive solution, to move the lock to the Parent class, has a different behaviour: I will not be able to call new Child1().Method1() and new Child2().Method1() simultaneously.
Is there any way to refactor the code below?
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 ...
}
}
}
I’m asking this because it’s not only 2 child classes, so the real problem is bigger.
Have a method implemented by each child class that provides lock policy and move Method1 to base class as in your other question.