Unable to inherit from a Thread Class in C# ?

后端 未结 2 1153
情话喂你
情话喂你 2021-01-04 18:43

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

相关标签:
2条回答
  • 2021-01-04 19:38

    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.

    0 讨论(0)
  • 2021-01-04 19:38

    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...
    }
    
    0 讨论(0)
提交回复
热议问题