Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TThread Not Releasing Handle

I have the following service written with Delphi 2007 which I find is not releasing the thread Handle. The functions CurrentMemoryUsage and GetOpenHandles are functions to return memory used and the number of handle used by the application. The Timer fires each second, creating a thread which is immediately destroyed. And I can see in my log the Number of Open Handles increments by one each time. This is a very basic threading question.

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;
like image 752
M Schenkel Avatar asked Aug 08 '26 15:08

M Schenkel


1 Answers

You have forgotten to call the inherited Destroy. That is what frees the system resources associated with the thread.

destructor TMyThread.Destroy;
begin
  appendtolog((FormatFloat('Memory used: ,.# K', 
    CurrentMemoryUsage / 1024))+',Number of Handles:'+inttostr(GetOpenHandles));
  inherited;
end;
like image 174
David Heffernan Avatar answered Aug 10 '26 15:08

David Heffernan