este es un ejemplo construido. No quiero publicar el código original aquí. Intenté extraer las partes relevantes sin embargo.Interfaces, métodos anónimos y fugas de memoria
Tengo una interfaz que administra una lista de oyentes.
TListenerProc = reference to procedure (SomeInt : ISomeInterface);
ISomeInterface = interface
procedure AddListener (Proc : TListenerProc);
end;
Ahora puedo registrar un oyente:
SomeObj.AddListener (MyListener);
procedure MyListener (SomeInt : ISomeInterface);
begin
ExecuteSynchronized (procedure
begin
DoSomething (SomeInt);
end);
end;
me pongo pérdidas de memoria. Tanto el método anónimo como las interfaces nunca se liberan. Sospecho que esto se debe a algún tipo de referencia circular aquí. El método anónimo mantiene viva la interfaz y la interfaz mantiene vivo el método anónimo.
dos preguntas:
- ¿Apoya que la explicación? ¿O me estoy perdiendo algo más aquí?
- ¿Hay algo que pueda hacer al respecto?
¡Gracias de antemano!
EDITAR: No es tan fácil de reproducir esto en una aplicación suficientemente pequeño como para publicar aquí. Lo mejor que puedo hacer ahora es lo siguiente. El método anónimo no quede liberado aquí:
program TestMemLeak;
{$APPTYPE CONSOLE}
uses
Generics.Collections, SysUtils;
type
ISomeInterface = interface;
TListenerProc = reference to procedure (SomeInt : ISomeInterface);
ISomeInterface = interface
['{DB5A336B-3F79-4059-8933-27699203D1B6}']
procedure AddListener (Proc : TListenerProc);
procedure NotifyListeners;
procedure Test;
end;
TSomeInterface = class (TInterfacedObject, ISomeInterface)
strict private
FListeners : TList <TListenerProc>;
protected
procedure AddListener (Proc : TListenerProc);
procedure NotifyListeners;
procedure Test;
public
constructor Create;
destructor Destroy; override;
end;
procedure TSomeInterface.AddListener(Proc: TListenerProc);
begin
FListeners.Add (Proc);
end;
constructor TSomeInterface.Create;
begin
FListeners := TList <TListenerProc>.Create;
end;
destructor TSomeInterface.Destroy;
begin
FreeAndNil (FListeners);
inherited;
end;
procedure TSomeInterface.NotifyListeners;
var
Listener : TListenerProc;
begin
for Listener in FListeners do
Listener (Self);
end;
procedure TSomeInterface.Test;
begin
// do nothing
end;
procedure Execute (Proc : TProc);
begin
Proc;
end;
procedure MyListener (SomeInt : ISomeInterface);
begin
Execute (procedure
begin
SomeInt.Test;
end);
end;
var
Obj : ISomeInterface;
begin
try
ReportMemoryLeaksOnShutdown := True;
Obj := TSomeInterface.Create;
Obj.AddListener (MyListener);
Obj.NotifyListeners;
Obj := nil;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Debería mostrarnos cómo funciona AddListener. –
Acabo de ponerlos en un 'TList .' –
jpfollenius
Todo el código que veo se ve bien. El problema debe estar en la parte oculta. ¿Puedes mostrar un ejemplo completo que produce la fuga? –