Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi check if TThread is still running

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?

like image 312
uacaman Avatar asked Jan 17 '14 16:01

uacaman


1 Answers

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:

  1. Use WaitFor to block until the thread completes. This will block the calling thread which will preclude showing UI, or responding to the user.
  2. Use MsgWaitForMultipleObjects in a loop, passing the thread handle. This allows you to wait until the thread completes, but also service the UI.
  3. Implement an event handler for the 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.

like image 105
David Heffernan Avatar answered Sep 16 '22 18:09

David Heffernan