Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a thread in delphi?

Tags:

In delphi, a method in TThread is terminate. It seems a subthread can not kill another thread by calling terminate or free. For example A(main form), B (a thread unit), C (another form).

B is sending data to main form and C (by calling syncronize), we tried to terminate B within C while B is executing by calling B.terminate. But this method does not work and B is still working until it ends in execute method.

Please help. Thank you in advance.

like image 332
Dylan Avatar asked Oct 28 '10 16:10

Dylan


1 Answers

You have to check for Terminate in the thread for this to work. For instance:

procedure TMyThread.Execute; begin   while not Terminated do begin     //Here you do a chunk of your work.     //It's important to have chunks small enough so that "while not Terminated"     //gets checked often enough.   end;   //Here you finalize everything before thread terminates end; 

With this, you can call

MyThread.Terminate; 

And it'll terminate as soon as it finishes processing another chunk of work. This is called "graceful thread termination" because the thread itself is given a chance to finish any work and prepare for termination.

There is another method, called 'forced termination'. You can call:

TerminateThread(MyThread.Handle); 

When you do this, Windows forcefully stops any activity in the thread. This does not require checking for "Terminated" in the thread, but potentially can be extremely dangerous, because you're killing thread in the middle of operation. Your application might crash after that.

That's why you never use TerminateThread until you're absolutely sure you have all the possible consequences figured out. Currently you don't, so use the first method.

like image 51
himself Avatar answered Sep 19 '22 12:09

himself