delphi - 如何在线程终止后自动执行FreeAndNill()

标签 delphi

目前我正在使用额外的线程来很好地释放线程后的内存。 在你问之前。不,我不能使用 FreeOnTerminate:=true 因为我需要 .waitfor。 我还需要 FreeAndNil(),因为只有这样我才能使用Assigned() 检查线程是否正在运行。示例代码。

procedure TForm1.Button1Click(Sender: TObject);
begin  

  SupervisorThread:= TSupervisorThread.Create(True);
  SupervisorThread.FreeOnTerminate:=false; //MUST BE FALSE!
  SupervisorThread.Priority := tpNormal;
  SupervisorThread.Resume;

end;

procedure TSupervisorThread.Execute;
begin

  CleaningThread:= TCleaningThread.Create(True);
  CleaningThread.FreeOnTerminate:=true;
  CleaningThread.Priority := tpNormal;
  CleaningThread.Resume;

  //some loops here

end;

procedure TCleaningThread.Execute;
begin

  if Assigned(SupervisorThread)=true then
  begin
    SupervisorThread.WaitFor;
    FreeAndNil(SupervisorThread);
  end;

end;

procedure TForm2.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin

  if Assigned(SupervisorThread)=false then CanClose:=true  
  else 
  begin
    CanClose:=false;
    ShowMessage('Cannot close form because SiupervisorThread is still working'); 
  end;

end;

最佳答案

使用TThread.OnTerminate事件:

private
  procedure DoTerminateEvent(Sender: TObject);

var
  isRunning: Boolean;

procedure TForm2.DoTerminateEvent(Sender: TObject);
begin
  isRunning := False;
end;

procedure TForm2.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  if (isRunning) then
  begin
    CanClose := false;
    ShowMessage('Cannot close form because SupervisorThread is still working')
  end else
    CanClose := true;
end;

创建线程时设置OnTerminate处理程序:

SupervisorThread := TSupervisorThread.Create(True);
...
SupervisorThread.OnTerminate := DoTerminateEvent;
SupervisorThread.Resume;

或者,将其作为参数传递给线程的构造函数:

TSupervisorThread = class(TThread)
public
  constructor Create(OnTerminatEvent: TNotifyEvent);
end;

procedure TThreadCustom.Create(OnTerminateEvent: TNotifyEvent);
begin
  inherited Create(True);
  OnTerminate := OnTerminateEvent;
end;

SupervisorThread := TSupervisorThread.Create(DoTerminateEvent);

关于delphi - 如何在线程终止后自动执行FreeAndNill(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43172384/

相关文章:

delphi - 有条件地防止“确定”按钮关闭对话框

Delphi 不兼容的类型

delphi - 单个 TIdHTTPServer 组件可以同时处理 http 和 https 请求吗?

delphi - 如何在 Spring4D 1.2 中更新数据库架构

delphi - 重载函数时不接受数组类型参数

delphi - 当我重新排列 TObjectList 时,为什么会收到 "invalid pointer operation"?

delphi - 更改 JvLoginDialog 的标题

delphi - Facebook 德尔福

windows - 是否有编程方式在 Windows 中获取短日期名称?

delphi - BDE 与 Delphi XE