TThread不释放句柄

时间:2012-01-27 16:12:02

标签: delphi delphi-2007

我有以下使用Delphi 2007编写的服务,我发现它没有发布线程句柄。函数 CurrentMemoryUsage GetOpenHandles 是返回使用的内存和应用程序使用的句柄数的函数。 Timer每秒触发一次,创建一个立即销毁的线程。我可以在我的日志中看到打开句柄数每次增加1。这是一个非常基本的线程问题。

TMyThread = class(TThread)
private
protected
  procedure Execute; override;
public
  constructor Create(CreateSuspended: Boolean);
  destructor Destroy; override;
end;


procedure TMyService.MyTimerTimer(Sender: TObject);
var
    MyThread : TMyThread;
begin
    MyThread := TMyThread.Create(True);
    MyThread.OnTerminate := ThreadTerminated;
    MyThread.FreeOnTerminate := True;
    MyThread.Resume;
end;

procedure TMyThread.Execute;
begin
  FreeOnTerminate := True;
end;

destructor TMyThread.Destroy;
begin
   appendtolog((FormatFloat('Memory used: ,.# K', CurrentMemoryUsage / 1024))+',Number of Handles:'+inttostr(GetOpenHandles)) ;
end;

constructor TMyThread.Create(CreateSuspended: Boolean);
begin
  inherited Create(CreateSuspended);
end;

procedure TMyService.ThreadTerminated(Sender: TObject);
begin
  appendtolog('thread terminiated');
end;

1 个答案:

答案 0 :(得分:7)

您忘记调用继承的Destroy。这就是释放与线程相关的系统资源的原因。

destructor TMyThread.Destroy;
begin
  appendtolog((FormatFloat('Memory used: ,.# K', 
    CurrentMemoryUsage / 1024))+',Number of Handles:'+inttostr(GetOpenHandles));
  inherited;
end;