Search code examples
multithreadingdelphithread-safetyterminatedelphi-2006

Delphi 2006 - What's the best way to gracefully kill a thread and still have the OnTerminate handler fire?


I have a thread that sometimes freezes (I suspect) due to a DLL call that never returns. In the general case, where you have calls to blocking routines like Indy, is there a way of recovering from this in such a way that the thread OnTerminate handler fires? Will this happen if I call TerminateThread?


Solution

  • TerminateThread() is an immediate brute-force termination. It will NOT let the OnTerminaate event fire. The only way OnTerminate can fire is if the thread's Execute() method exits through normal means, whether that be gracefully or by raising an uncaught exception (which will set the thread's FatalExpection property).

    In the case of Indy specifically, a blocking socket operation can be aborted by disconnecting the socket from the context of another thread. That is not usually possible with blocking DLL functions, unless they expose that kind of functionality in their API.