在Qt中,每個對象associated with a thread都有一個很好的習慣用法,因此它的所有事件處理函數將會是only run in that thread(除非直接調用)。有沒有類似於.NET中的Qt :: QueuedConnection的東西?
在C#/ .NET中是否還有類似的東西?如果不是,你會如何開始寫自己的?
實施例:
// 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;
};
和
// 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();
}
將輸出:
Main thread is 3916
"Foo" in thread 3824
"Foo" in thread 3824
"Bar" in thread 3920
"Foo" in thread 3824
...
只是一個供參考 - WPF的調度** **是的的SynchronizationContext的形式是WPF特定... – 2011-12-02 18:23:14