任务WORK在thread里面运行后,如果想停止任务(而不是简单终止线程),用线程安全的方式用槽信号来触发任务停止条件时,不起作用,因为线程内需要等任务(dowork)自然完成后,才会接收其他槽信号队列。如果直接用跨线程的方式执行实例self.work.stop,反而能够立即停止任务。只是隐约感觉这种方式不太正规,请问有没有其他方式?
class Work(QObject):
update_process = pyqtSignal(int)
update_completed = pyqtSignal()
.....ini_thing....
def dowork(self):
self.var = 0
while self.var < 10 and self._running == True
self.var += 1
self.update_process.emit(self.var)
self.update_completed.emit()
def stopwork(self):
self._running = false
class UiTest(QDialog):
.....UI-thing....
self.work = Work()
self.thread = QThread()
self.work.moveToThread(self.thread)
self.thread.started.connect(self.work.dowork)
self.work.update_process.connect(self.currentStep.setValue)
self.worker.update_completed.connect(lambda:print('work finished'))
self.btnDoWork.clicked.connect(self.work.dowork)
self.btnStopThread.clicked.connect(self.stop_thread)
self.btnStartThread.clicked.connect(self.start_thread)
self.thread.finished.connect(lambda: print('thread finished'))
def start_thread(self):
self.thread.start()
def stop_thread(self):
self.thread.quit()
self.thread.wait()
self.work.stopwork
。。。。APP Thing。。。。。。。