gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:11:00 26 4
gpt4 key购买 nike

目前我正在使用额外的线程来很好地释放线程后的内存。在你问之前。不,我不能使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com