views:

46

answers:

1

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 
...
+3  A: 

The closest analogy to this in .NET would likely be SynchronizationContext.

This is used, for example, by the Task Parallel Library for marshalling continations back to a UI thread.

There isn't, however, a built-in implementation that works on any thread. It's fairly easy to write one using BlockingCollection<T> in .NET 4, but it isn't included in the Framework. It also is somewhat different, in that it doesn't automatically marshal the events back onto that thread for you - it's more of a building block that provides the functionality required for this type of operation.

Reed Copsey