Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the correct way to wait for a Thread.finalization and keep my application responsive

Actually i am using this code and works ok, but i 'am wondering if is the correct way.

  while WaitForSingleObject(MyThread.Handle, 0) = WAIT_TIMEOUT do
    Application.ProcessMessages;

  ShowMessage('i am done');
like image 275
Salvador Avatar asked Nov 16 '10 03:11

Salvador


3 Answers

The VCL TThread class has its own WaitFor() method that pumps the main message queue internally when called within the main thread context:

MyThread.WaitFor; 
ShowMessage('i am done'); 
like image 88
Remy Lebeau Avatar answered Oct 25 '22 16:10

Remy Lebeau


Calling Application.ProcessMessages is generally considered a code smell. Let your main thread idle if it's got nothing to do.

If you ran a company and needed one of your workers to run to the store and grab some much-needed supplies, would you then pace by the door until he got back, or would you prefer to sit in your office and rest and wait for him, and find out that the supplies are here because you hear him walk through the door? Either way, he'll take the same amount of time, but the first way's gonna wear your legs out.

Similarly, instead of having your UI watch the thread, have the thread report back to the UI. One way to do this is to have the thread use PostMessage to send a custom message to the form that launched it once it's finished, and put a message handler on the form to respond to it.

like image 8
Mason Wheeler Avatar answered Oct 25 '22 15:10

Mason Wheeler


It looks correct (if correct means it do the work). What I would change is to wait for a bit more time (50ms looks good to maintain the application responsive) while not eating CPU.

while WaitForSingleObject(MyThread.Handle, 50) = WAIT_TIMEOUT do
  Application.ProcessMessages;
ShowMessage('i am done');

Sure there are other ways to do it... <joke>but I usually apply one of the main engineering principles:

if it works, don't touch it!</joke>

like image 2
jachguate Avatar answered Oct 25 '22 15:10

jachguate