In Qt, there is a nice idiom to have each object associated with a thread, so that all its event handlers will only run in that thread (unless called directly, of course).
Is there anything even remotely like that in C#/.NET? If not, how would you start writing your own?
Example:
// threaded.h
#include <QThread>
#include <QDebug>
#include <QtGlobal>
class ThreadedObject : public QObject {
Q_OBJECT
public:
ThreadedObject(const QString &name){
Name = name;
// the default QThread implementation is an empty event loop
Thread = new QThread(this);
moveToThread(Thread);
Thread->start();
}
public slots:
void tick() {
qDebug() << Name << "in thread" << (int)QThread::currentThreadId();
}
private:
QThread *Thread;
QString Name;
};
and
// main.cpp
#include <QtCore/QCoreApplication>
#include <QTimer>
#include "threaded.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ThreadedObject *foo = new ThreadedObject("Foo");
QTimer footimer;
QObject::connect(&footimer, SIGNAL(timeout()), foo, SLOT(tick()));
ThreadedObject *bar = new ThreadedObject("Bar");
QTimer bartimer;
QObject::connect(&bartimer, SIGNAL(timeout()), bar, SLOT(tick()));
qDebug() << "Main thread is" << (int)QThread::currentThreadId();
footimer.start(1300);
bartimer.start(3240);
return a.exec();
}
will output:
Main thread is 3916
"Foo" in thread 3824
"Foo" in thread 3824
"Bar" in thread 3920
"Foo" in thread 3824
...