Unable to inherit from a Thread Class in C# ?

后端 未结 2 1170
情话喂你
情话喂你 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.

提交回复
热议问题