The class Thread is a sealed class meaning it cannot be inherited from and I need an instance of a reusable Thread that should inherit from the Thread class. Does anyone have an idea how i can reuse tread ?
            Asked
            
        
        
            Active
            
        
            Viewed 2.0k times
        
    14
            
            
        
        Abdul Munim
        
- 18,869
 - 8
 - 52
 - 61
 
        Kenzo
        
- 1,767
 - 8
 - 30
 - 53
 
- 
                    6Try composition? – Erix Nov 14 '11 at 15:00
 - 
                    1What sense does a resuable thread make when a thread is not reusable from the operating point of view? – TomTom Nov 14 '11 at 15:04
 - 
                    Why don't you use ThreadPool instead? – L.B Nov 14 '11 at 15:09
 - 
                    2It's not my business, but you are going to do something awful and dangerous. Consider about sharing your main problem with community, and I'm sure we could find better solution. – Alex Zhevzhik Nov 14 '11 at 15:13
 
2 Answers
32
            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.
        rossipedia
        
- 56,800
 - 10
 - 90
 - 93
 
5
            
            
        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...
}
        Tudor
        
- 61,523
 - 12
 - 102
 - 142