FreeAndNil过程是否还释放在线程中创建的TStringList?

时间:2018-07-25 18:59:09

标签: delphi

for x:=0 to NumberOfWaitingThreads-1 do
begin

  WaitForThread:=TWaitForThread.Create(true);
  ArrayOfHandles[x]:=WaitForThread.Handle;
  WaitForThread.FreeOnTerminate:=false;
  WaitForThread.CommandLineList:=TStringList.Create; 
  WaitForThread.CommandLineList.Text:=CommandList.Text;
  WaitForThread.Resume;

end;

CommandList.Free;

repeat
  WaitStatus:=WaitForMultipleObjects(NumberOfWaitingThreads,@ArrayOfHandles[0], True, 100);
until WaitStatus<>WAIT_TIMEOUT;

FreeAndNil(WaitForThread);

FreeAndNil(WaitForThread)是否也免费在此处创建的TStringList WaitForThread.CommandLineList:= TStringList.Create;

1 个答案:

答案 0 :(得分:3)

  

FreeAndNil(WaitForThread)是否也免费TStringList在此处创建WaitForThread.CommandLineList:=TStringList.Create;

FreeAndNil(WaitForThread)仅释放线程本身,而不释放线程创建的任何对象。

因此,答案是否定的,您将必须在线程析构函数中执行此操作。


请注意,如果NumberOfWaitingThreads> 1,则将泄漏除最后一个线程对象之外的所有线程对象。通过声明TWaitForThread的数组来解决此问题:

var
  WaitForThreadArr : array of TWaitForThread;
...

SetLength(WaitForThreadArr,NumberOfWaitingThreads);
for x := 0 to NumberOfWaitingThreads-1 do
begin

  WaitForThreadArr[x] := TWaitForThread.Create(true);
  ArrayOfHandles[x] := WaitForThreadArr[x].Handle;
  WaitForThreadArr[x].FreeOnTerminate := false;
  WaitForThreadArr[x].CommandLineList := TStringList.Create; 
  WaitForThreadArr[x].CommandLineList.Text := CommandList.Text;
  WaitForThreadArr[x].Start;
end;

CommandList.Free;

repeat
  WaitStatus := WaitForMultipleObjects(NumberOfWaitingThreads,@ArrayOfHandles[0], True, 100);
until WaitStatus <> WAIT_TIMEOUT;

for x := 0 to NumberOfWaitingThreads - 1 do begin
  Free(WaitForThreadArr[x]);
end;