How to kill a thread in delphi?

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.

Leave a Comment