目前我正在使用額外的線程來很好地釋放線程後的內存。 在你問之前。不,我不能使用FreeOnTerminate:= true,因爲我需要.waitfor。 我也需要FreeAndNil(),因爲只有這樣我才能檢查線程是否使用Assigned()運行。示例代碼。創建線程時如何在線程終止後自動執行FreeAndNill()
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
處理:
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;
使用的事件信號,呃,事件 –
如果你想的唯一的事情就是要知道如果線程完成後,分配'OnTerminate'處理器到線程。 –
我必須指出,一個線程被'SupervisorThread.WaitFor;'所阻塞的另一個線程看起來有點毫無意義。記住線程的要點是允許代碼執行_concurrently_。您的示例引發了以下問題:爲什麼不能在Supervisor結束時運行清理?爲什麼你必須在前面創建清潔對象;你能等到主管完成嗎?如果你想「終止」清洗會發生什麼? - 你不能,因爲它不是在'Terminated'循環中。 –