L
L
l0cked2019-05-14 16:37:52
Python
l0cked, 2019-05-14 16:37:52

How to stop asyncio loop in QThread?

Good afternoon, I'm writing a utility, I ran into a problem: when closing, everything just simply freezes ...
As I understand it, the event loop in QThread is not closed. So the question is:
Tell me how to close the event loop correctly.

The code
from PyQt5.QtCore import QThread, QObject, pyqtSlot
from PyQt5.QtWidgets import QMainWindow, QApplication
import asyncio
import websockets


class ExampleWorker(QObject):
    def __init__(self):
        super().__init__()


    @pyqtSlot()
    def start(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        self.loop.run_until_complete(websockets.serve(self.echo, 'localhost', 8765))
        self.loop.run_forever()


    async def echo(self, websocket, path):
        async for message in websocket:
            await websocket.send(message)


class Example(QMainWindow):

    def __init__(self):
        self.app = QApplication([])
        super().__init__()

        self.obj = ExampleWorker()
        self.thread = QThread()
        self.obj.moveToThread(self.thread)
        self.thread.started.connect(self.obj.start)
        self.thread.start()

        self.show()
        self.app.exec_()


    def closeEvent(self, event):
        self.thread.quit()
        self.thread.wait()


Example()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question