同事写的一个简单的测试程序,用定时器往TList里加对象,另外开一个线程进行扫描TList,发现里面有对象就释放掉对象。但是时间长了会内存泄露,在任务管理器里可以看到进程不断增加。看了半天没找出问题,代码如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Timer1: TTimer;
Button3: TButton;
procedure Timer1Timer(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
Unit2;
var
mythread:repthread;
{$R *.dfm}
procedure TForm1.Timer1Timer(Sender: TObject);
var
newtestclass:testclass;
begin
mythread.cs.Enter;
newtestclass:=testclass.Create;
newtestclass.val:=100;
// newtestclass.buflen:=100;
// setlength(newtestclass.buf,newtestclass.buflen);
mythread.replist.Add(newtestclass);
mythread.cs.Leave;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Timer1.Enabled:=true;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Timer1.Enabled:=false;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
mythread:=repthread.Create(false);
end;
end.
unit Unit2;
interface
uses
Classes,SyncObjs,SysUtils;
type
testclass=class
val:integer;
// buf:array of byte;
// buflen:integer;
// public
// destructor Destroy; override;
end;
type
repthread = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
public
replist:TLIST;
RUNing:boolean;
cs:TCriticalSection;
end;
implementation
uses Unit1;
{ repthread }
procedure repthread.Execute;
var
ACTtestclass:testclass;
Index: Integer;
begin
{ Place thread code here }
replist:=TLIST.Create;
RUNing:=true;
cs:=TCriticalSection.Create;
while RUNing do
begin
cs.Enter;
if replist.Count>0 then
begin
{ ACTtestclass:=testclass(replist.Items[0]);
replist.Delete(0);
// setlength(ACTtestclass.buf,0);
ACTtestclass.Destroy;
replist.Pack; }
Index := RepList.Count - 1;
if RepList.Items[Index] <> nil then
begin
TObject(RepList.Items[Index]).Free;
RepList.Delete(Index);
end;
end
else
begin
sleep(100);
end;
cs.Leave;
end;
cs.Free;
end;
{destructor testclass.Destroy;
begin
inherited;
end;}
end.