Failed to inherit from Thread class in C #?

The Thread class is a private class, meaning that it cannot be inherited, and I need an instance of the reusable Thread that must inherit from the Theme class. Does anyone have an idea how I can reuse a protector?

+7
source share
2 answers

As you yourself noted, Thread is a private class. Obviously, this means that you cannot inherit it. However, you can create your own BaseThread class, which you can inherit and override to provide custom functions with 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 override void RunThread() { // Do some stuff } } 

You get the idea.

+21
source

A preferred alternative to using Inheritance is to use a composition. Create your class and enter a member of type Thread . Then map the methods of your class to call the methods from the Thread member and add any other methods you might want. Example:

 public class MyThread { private Thread thread; // constructors public void Join() { thread.Join(); } // whatever else... } 
+4
source

All Articles