I’ve always wondered is there a better way that I should be writing some of my procedures, particularly ones that take a long time to finish.
I have always run everything off the Main GUI Thread which I now understand and realise is bad because it will make the Application unresponsive, Application.ProcessMessages will not really help here.
This makes me think I need to use TThreads for lengthy operations such as copying a file for example. This is also made me wonder how some Applications give you full control, eg allow you to pause, resume and or stop the operation.
I have about 3 lengthy operations in a personal project I am working on which I display a dialog form with a TProgressBar on. Whilst this does work, I feel it could be done much better. These progress dialogs could be shown for such a long time that you may want to cancel the operation and instead finish the job later.
As I said, currently I am running of the Main Gui Thread, do I instead need to use TThreads? I am not sure how or where to start implementing them as I have not worked with them before. If I do need threads do they offer what I need such as pausing, resuming, stopping an operation etc?
Basically I am looking for a better way of handling and managing lengthy operations.
Yes, this is definitely a case where you need a thread to do the task.
A little example how to pause/resume a thread and cancel the thread.
Progress is sent to the main thread through a PostMessage call.
The pause/resume and cancel are made with
TSimpleEventsignals.Edit: As per the comments from @mghie, here is a more complete example:
Edit 2: Showing how to pass a procedure for the thread to call for the heavy work.
Edit 3: Added some more features and a test unit.
Just call
MyThread.Paused := trueto pause andMyThread.Paused := falseto resume the thread operation.To cancel the thread, call
MyThread.Free.To receive the posted messages from the thread, see following example:
And the form: