【发布时间】:2014-11-18 04:47:45
【问题描述】:
那里有人可以解释为什么我的代码会导致 4KB 的内存泄漏,查看 TaskManager。 Delphi 2005,服务应用程序:
unit uMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs,
ExtCtrls;
type
TgwDebugService_s = class(TService)
Timer1: TTimer;
procedure Timer1Timer(Sender: TObject);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
procedure ServiceExecute(Sender: TService);
private
{ Private declarations }
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
var
gwDebugService_s: TgwDebugService_s;
implementation
{$R *.DFM}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
gwDebugService_s.Controller(CtrlCode);
end;
function TgwDebugService_s.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TgwDebugService_s.ServiceExecute(Sender: TService);
begin
// Service is Fired
while not Terminated do
ServiceThread.ProcessRequests(True);// wait for termination
end;
procedure TgwDebugService_s.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
// Service stops
end;
procedure TgwDebugService_s.Timer1Timer(Sender: TObject);
var
sl : TStringList;
begin
Timer1.Enabled := False;
Sleep(1000);
sl := TStringList.Create;
try
//if FileExists( 'c:\OnlyOnMyPc\test.txt' ) then
sl.LoadFromFile( 'c:\OnlyOnMyPc\test.txt' ); // remove this line and will be find
sl.Add( 'Test @ ' + FormatDateTime( 'dd.mm.yyyy hh:mm:ss.z', Now ) );
sl.SaveToFile( 'c:\OnlyOnMyPc\test.txt' );
finally
sl.Clear;
FreeAndNil( sl );
end;
Timer1.Enabled := True;
end;
end.
感谢您的时间和帮助。
干杯。 英镑
【问题讨论】:
-
我没有在您的代码中看到任何内存泄漏,任务管理器不是合适的工具,请在完全调试模式下使用 FastMM。不过有几个改进点。 a) 不要实现 ServiceExecute,它已经开箱即用。 b) 不要使用 TStringList 在文件中添加一行,记住
LoadFromFile将整个文件读入内存,当日志文件变大时,这段代码会变得越来越慢(并且会占用内存)。在您的情况下,附加到带有TFileStream的文件会更合适。 -
为什么你的 Timer 事件中有
Sleep();它是阻塞代码,首先使用 Timer 的原因之一是避免这种情况。另外,你不需要在销毁sl之前调用sl.Clear;销毁列表时会自动清除该列表。最后FreeAndNil对局部变量来说是严重的过度杀伤;sl.Destroy会很好。 -
@Craig 我认为 Free 会比 Destroy 更正常。这样您就可以避免在代码的某些部分(析构函数)中使用 Free 并在其他部分(方法)中使用 Destroy。
-
因为@whosrdaddy 已经很伤心任务管理器不是监控内存泄漏的好工具。为什么?任务管理器显示某个应用程序分配了多少内存,但该特定应用程序实际上使用的内存可能比那个特定时间少得多。
-
@CraigYoung 显然我也知道。但你留下的评论并没有这么说。天真的开发者可能会开始在析构函数中调用
Destroy,结果并不好。
标签: delphi memory-leaks tstringlist