TThread.OnTerminate 执行线程

TThread.OnTerminate executing thread

TThread.OnTerminate 的 Delphi 帮助指出:

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.

即使在主线程以外的线程中创建线程也是如此吗?

那么,OnTerminate 是在创建 TThread 的线程中调用的,还是在主线程中调用的? IDE 没有告诉我这个。调试时,我在 OnTerminate 事件中看不到活动线程。 :-/

文档是正确的。默认情况下,OnTerminate 事件处理程序始终在主线程中 运行。在内部,TThread.DoTerminate()(在线程的 Execute() 方法退出后调用)使用 TThread.Synchronize() 调用处理程序:

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;

如果您希望 OnTerminate 处理程序在终止线程(或您想要的任何其他线程)的上下文中 运行,您可以简单地覆盖 DoTerminate() 来调用处理程序无论你想要什么,例如:

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;