在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
无意中想到Delphi中没有垃圾回收机制,于是想看看有没有人已经做了这方面的工作。 后来发现了这篇文章,写的很不错,借过来留作参考,只可惜不知道作者。 转自:http://developer.51cto.com/art/200510/7129.htm 1 缘起 名称:呼叫处理模块的压力测试工具,分为客户端和服务端。
仔细检查程序后,我仍然认为这一切简直是不可思议!而且,本来用于对别的程序进行测试的程序自身却出现这类问题,几乎让我无地自容!
procedure Txxxx.ServerClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); Begin … FLines.DestroyLineBySocket(Socket);//正是这一句,在不合适的时机释放了对象 … End;
FLine.DoSomething; FLine.SendSocketData; FLine.DoOtherThings;
2.2 解决方案
3.2 实现代码unit untGarbagCollector;
interface uses Classes; type TGarbagCollector = Class(TObject) private FList: TThreadList; public constructor Create; destructor Destroy; override; procedure Put(const AObject: TObject); procedure Recycle(const MaxCount: Integer); end; function GarbagCollector: TGarbagCollector; implementation var _GarbagCollector: TGarbagCollector; function GarbagCollector: TGarbagCollector; begin if not Assigned(_GarbagCollector) then _GarbagCollector := TGarbagCollector.Create; result := _GarbagCollector; end; { TGarbagCollect } constructor TGarbagCollector.Create; begin FList := TThreadList.Create; end; destructor TGarbagCollector.Destroy; begin try Recycle(FList.LockList.Count); finally FList.UnlockList; end; FList.Free; end; procedure TGarbagCollector.Put(const AObject: TObject); begin try FList.LockList.Add(AObject); finally FList.UnlockList; end; end; procedure TGarbagCollector.Recycle(const MaxCount: Integer); var I: Integer; AList: TList; begin AList := FList.LockList; try I := 0; while (AList.Count > 0) and (I < MaxCount) do begin TObject(AList.Last).Free; AList.Delete(AList.Count - 1); Inc(I); end; finally FList.UnlockList; end; end; initialization finalization if Assigned(_GarbagCollector) then _GarbagCollector.Free; end. 3.3 使用举例
AObject := TObject.Create; GarbagCollector.Put(AObject);
可以在定时器、线程以及其他场合调用Recycle方法。 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论