PDA

View Full Version : Best way to terminate a copy thread?



scarleton
13th July 2010, 04:29
I have a common scenario: a dialog show the progress of copying lots of files and has a cancel button. The copy process is taking place in a QThread class which fires signals as files are copied and exit's the run() method when finished. the dialog gets the finished signal and closes itself.

Question: What is the best way for the dialog to shutdown the thread if the cancel button is clicked? In the old days I would simply have the dialog set a property on the thread class that the thread class would check after copying each file. If it was set, exit. Is there a better way to do this in Qt? I ask because there are other ways of doing it in .Net.

Sam

tbscope
13th July 2010, 05:43
I assume you have an event loop in your thread (you need to to deal with events and signals and slots).
Then you can use quit() to exit the event loop. But before quiting, stop the copy process gracefully. Either proceed with the current file till it is copied and then stop for the rest of the files and quit. Or stop copying immediatly and delete the part of the copied file before quiting the event loop.
When a thread is finished, it emits the finished signal.

You might want to add a slot to do all this and connect it to the cancel button.

Beware of using signals and slots in threads.
http://labs.trolltech.com/blogs/2010/06/17/youre-doing-it-wrong/