Unable to inherit from a Thread Class in C# ?

As you yourself noted, Thread is a sealed class. Obviously this means you cannot inherit from it. However, you can create your own BaseThread class that you can inherit and override to provide custom functionality using Composition.

abstract class BaseThread
{
    private Thread _thread;

    protected BaseThread()
    {
        _thread = new Thread(new ThreadStart(this.RunThread));
    }

    // Thread methods / properties
    public void Start() => _thread.Start();
    public void Join() => _thread.Join();
    public bool IsAlive => _thread.IsAlive;

    // Override in base class
    public abstract void RunThread();
}

public MyThread : BaseThread
{
    public MyThread()
        : base()
    {
    }

    public override void RunThread()
    {
        // Do some stuff
    }
}

You get the idea.


A preferable alternative to using Inheritance is to use Composition. Create your class and have a member of type Thread. Then map the methods of your class to call methods from the Thread member and add any other methods you may wish. Example:

public class MyThread 
{
    private Thread thread;
    // constructors

    public void Join()
    {
        thread.Join();
    }

    // whatever else...
}

Tags:

C#