I am using TThread, i just need to find out if thread is still running and terminate the application if it takes to long.
Ex:
MyThread := TMyThread.Create;
MyThread .Resume;
MyThread.Terminate;
total := 0;
while MyThread.isRunning = true do // < i need something like this
begin
// show message to user to wait a little longer we are still doing stuff
sleep(1000);
total := total + 1000;
if total > 60000 then
exit;
end;
Is this possible with Delphi?
The straight answer to your question is the Finished
property of TThread
. However, I don't recommend that. It leads you to that rather nasty Sleep
based loop that you present in the question.
There are a number of cleaner options, including at least the following:
WaitFor
to block until the thread completes. This will block the calling thread which will preclude showing UI, or responding to the user.MsgWaitForMultipleObjects
in a loop, passing the thread handle. This allows you to wait until the thread completes, but also service the UI.OnTerminate
event. This allows you to be notified in an event driven manner of the thread's demise.I recommend that you use one of these options instead of your home-grown Sleep
based loop. In my experience, option 3 generally leads to the cleanest code. But it is hard to give rigid advice without knowing all the requirements. Only you have that knowledge.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With