So, I have a base class which has a private locking object like so:
class A
{
private object mLock = new object();
public virtual void myMethod()
{
lock(mLock)
{
// CS
}
}
}
This locking object is used for most of A‘s operations… because they need to be thread safe.
Now, lets say I inherit from A like so:
class B : public A
{
public override void myMethod()
{
lock(???)
{
// CS of mymethod here
// Call base (thread safe alread)
base.myMethod();
}
}
}
What is the convention for making B thread safe? Should B also have a private locking object like A does? What if I need to call the base method like above?
I guess I’m just curious what the convention is for making subclasses thread safe when the base class is already thread safe. Thanks!
Edit: Some are asking what I mean by “thread safe”… I’ll clarify by adding that I’m trying to achieve thread safety through mutual exclusion… Only one thread at a time should be executing code which may alter the state of the object.
You would potentially expose the lock used by A:
If B had its own lock object, you could easily end up with:
As locks are recursive in .NET (for better or worse), if your override locks on the same object as A’s implementation, it’s fine to call
base.myMethodand recursively acquire/release the lock.Having said all of this, I’m keen on making most classes non-thread safe or immutable (only classes which are about threading need threading knowledge) and most classes don’t need to be designed for inheritance IMO.