How can I terminate a thread in a proper way? When the thread finishes, it is still in memory. I'm using Delphi 2010 (Update 5).
The way I usually describe the issues of thread termination is to stress co-operation. You should not terminate a thread. Instead you should notify the thread that you want it to terminate. You then politely wait until it has terminated.
The reasons for this are manifest. Only the thread knows how to terminate itself. Only the thread knows what locks it holds, what resources it needs to free etc.
The same arguments apply if you wish to pause or suspend a thread's execution. You should ask to it do so and then let the thread find a convenient moment when it is safe to do so.
With a Delphi TThread
the standard way to request termination is to call Thread.Terminate
. This does nothing more than to set a flag in the thread object. That is the request. The response is initiated by the thread code inside TThread.Execute
. That should regularly check the value of its Terminated
property. When that is found to be true, it should exit from the function. Naturally any tidy up (release locks, return resources etc.) should be performed before calling exit.