How to kill a thread in delphi?

Solution 1:

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.

Solution 2:

Actually,

currently most voted answer to this question is incorrect (so as 34 upvoters...) in regard how to forcefully kill a thread.

You do not use ThreadId as a parameter to TerminateThread procedure. Using ThreadId will cause most likely an "Invalid handle" error or in worse case scenerio - will kill a different thread.

You should pass a thread handle as a parameter:

TerminateThread(MyThread.Handle);

More about differences between thread's handle and id can be found here.

Edit

Seems @himself corrected his mistake after seeing my answer, so this is no longer relevant.

Solution 3:

Terminate does not kill a thread; it sets the Terminated property to inform the thread that it needs to terminate. It's the thread's responsibility to watch for Terminated and shut itself down gracefully.

Solution 4:

All the Terminate method does is it sets the Terminated property to true. So you have to manually keep checking that property and then exit the thread method when it is set to true.