Is it possible to inherit from the Thread class and override the Start method?
Causes the operating system to change the state of the current instance to Running. Causes the operating system to change the state of the current instance to Running, and optionally supplies an object containing data to be used by the method the thread executes.
Threading. Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread. When a C# program starts execution, the main thread is automatically created.
The Thread constructor takes a ThreadStart delegate as a parameter and creates a new thread. The parameter of the ThreadStart is the method that is executed by the new thread. Once a thread it created, it needs to call the Start method to actually start the thread.
using System.Threading;
namespace NGrubb.Threading {
public abstract class BaseThread {
private Thread m_thread;
public BaseThread() {
m_thread = new Thread( Run );
}
public void Start() {
m_thread.Start();
}
protected abstract void Run();
}
}
Regarding why someone would want to do this: a lot of languages (e.g. Java) and/or thread APIs (e.g. Qt) allow developers to implement threads by inheriting from a "thread" base class, and then overloading a method that implements the thread routine.
Having used this model extensively in Qt, I actually find it very handy--instead of having threads target some function or method, which often leads to weird and/or convoluted code, the whole thread is contained inside of an object.
Here's example code using the Qt API:
class MyThread : public QThread
{
Q_OBJECT
protected:
void run();
};
void MyThread::run()
{
...something I need threaded...
}
QThread is Qt's threading base class. To use MyThread, create an instance of the thread object and call QThread::start(). The code that appears in the run() reimplementation will then be executed in a separate thread.
What's nice about this is I think it lets you really contain everything a thread needs inside a single object, and (in my experience), it makes for a very coherent object model. I don't think it meets everyone's needs, but I was a bit surprised that C# doesn't have such a basic threading model to be honest.
I definitely don't buy that C#'s Thread class is sealed because of kernel complexity; if Qt can supply a cross-platform threading library that allows inheritance of QThread, I see no real reason MSFT couldn't provide the same capability in a threading class in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With