QRunnable trying to abort a task

怎甘沉沦 提交于 2020-01-16 08:04:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!