The Delphi help for TThread.OnTerminate
states that:
The method assigned to the OnTerminate event is executed in the context of the main thread rather than the context of the thread being terminated.
Is this even the case when the thread is created in another thread than the main thread?
So, is the OnTerminate
called in the thread that created the TThread
, or is it called in main thread? The IDE does not tells me this. When I debug, I see no active thread in the OnTerminate
event. :-/
The documentation is correct. The
OnTerminate
event handler is always run in the main thread by default. Internally,TThread.DoTerminate()
(which is called after the thread'sExecute()
method exits) usesTThread.Synchronize()
to call the handler:If you want the
OnTerminate
handler to run in the context of the terminating thread (or any other thread you want), you can simply overrideDoTerminate()
to call the handler however you want, eg: