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's Execute()
method exits) uses TThread.Synchronize()
to call the handler:
function ThreadProc(Thread: TThread): Integer;
var
...
begin
...
try
if not Thread.Terminated then
try
Thread.Execute;
except
...
end;
finally
...
Thread.DoTerminate;
...
end;
end;
procedure TThread.DoTerminate;
begin
if Assigned(FOnTerminate) then Synchronize(CallOnTerminate);
end;
procedure TThread.CallOnTerminate;
begin
if Assigned(FOnTerminate) then FOnTerminate(Self);
end;
If you want the OnTerminate
handler to run in the context of the terminating thread (or any other thread you want), you can simply override DoTerminate()
to call the handler however you want, eg:
type
TMyThread = class(TThread)
...
protected
...
procedure Execute; override;
procedure DoTerminate; override;
...
end;
procedure TMyThread.Execute;
begin
...
end;
procedure TMyThread.DoTerminate;
begin
// do whatever you want here, but DON'T call inherited!
if Assigned(OnTerminate) then OnTerminate(Self);
end;
OnTerminate
handler and can see that its thread ID is 12888. And if I put a breakpoint in some GUI code (like a button'sOnClick
handler, the main form'sOnCreate
handler, a menu item handler etc.) I see that the main GUI thread is 12888. My conclusion is therefore, ... Well, I think you can guess it! :) – Andreas Rejbrand Jan 20 at 20:51