Search code examples
c#inheritancethread-safetyabstract-class

Making a thread safe class from an abstract class


A question of design. I know that this method is thread safe, but from a design point of view, is there any better way to do this?

I have an abstract class (not thread safe):

public abstract class Class1
{
    protected someobject myobject;

    public Class1()
    {
       myobject = new someoject();
    }

    public virtual void proc1()
    {
      // do something with my object
    }

   public virtual void proc2()
    {
      // do something with my object
    }

  public virtual void proc3()
    {
      // do something with my object
    }
}

Now I want to make a descendent from this class that needs to be thread safe, so I do:

public class Class2: Class1
{
    private static readonly object obj = new object();


    public override void  proc1()
    {
      lock(obj)
      {
          base.proc1();
      }
    }

   public override void proc2()
   {
      lock(obj)
      {
          base.proc2();
      }
    }

   public override void proc3()
    {
      lock(obj)
      {
          base.proc3();
      }
    }
}

I could make the base thread safe but I have some other classes that inherits from the same base and don't need thread safety, so I don't want to force thread safety into it. Any problems with this kind of design? It's a bit tedious if the base has many public members....


Solution

  • In case you want to operate with Class1 (or a descendant class for that matter) in a thread safe manner, you should use encapsulation instead of inheritance as Kevin Gosse stated. Inheritance should not be used in this way, because if Class1 has more methods that are not virtual (maybe even public) that will change the object's internal state you will not have any control on them. You should take and encapsulate a class that inherits Class1 and then expose methods that will be called as a thread safe methods.

    Even if you do control Class1 design, it will be a poor design to think of the Thread safe inheritor (Class2) every time you are adding or changing Class1's methods