【发布时间】:2011-05-01 12:54:55
【问题描述】:
在 Qt 中,有一个很好的习惯用法是让每个对象都有associated with a thread,这样它的所有事件处理程序都会only run in that thread(当然,除非直接调用)。
在 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
...
【问题讨论】:
标签: c# .net multithreading qt thread-safety