M Schenkel
M Schenkel

Reputation: 6364

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;

Upvotes: 3

Views: 557

Answers (1)

David Heffernan
David Heffernan

Reputation: 613541

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;

Upvotes: 7

Related Questions