问题
Is it possible to abort a QRunnable task?
I can't find any way to do it even in the documentation.
Thanks a lot
回答1:
No, you cannot abort a QRunnable task.
The only way to dirty-abort a thread in Qt is through QThread::terminate()
(which is discouraged).
QThreadPool
uses QThread
behind-the-scenes to run QRunnable tasks, but it doesn't provide a way for developers to call QThread::terminate()
. Therefore, QRunnable cannot be aborted.
I recommend redesigning your application -- refer to Multithreading Technologies in Qt to get an overview of all the ways you can use threads, and select a solution that matches your use case.
回答2:
Qt shares a thread object model similar to many other frameworks (the .NET languages and Java come to mind). In these type of frameworks, it is generally discouraged to try to "abort" a thread. Other threading implementations (like POSIX) are largely the same way. It's bad practice to dirty-kill a thread.
Instead, construct your logic inside run() in such a way that you can put "checkpoints" in every so often to determine if the run() function can safely terminate. These checkpoints should check a flag (or some other sentinel) that indicates that the thread should end.
来源:https://stackoverflow.com/questions/59571209/how-to-safely-stop-or-terminat-a-qrunnable-or-qthread-object-in-the-gui