Jump to content
pyscripter

Memory leak with anonymous methods.

Recommended Posts

This is a simplified version of what I had in my app.

procedure Test();
var
  TerminateProc: TThreadProcedure;
  S: string;
begin
  S := 'Terminated';

  TerminateProc :=
    procedure
    begin
      ShowMessage(S);
    end;

  TThread.CreateAnonymousThread(
  procedure
  begin
    // Do stuff

    TThread.Queue(nil, TerminateProc);
    TerminateProc := nil; //  Memory leak without this
  end).Start;
end;

I had to insert the statement with the comment "Memory leak without this"  to avoid memory leaks.   Any idea why the compiler does not free TerminateProc on its own?  Is this a compiler bug?

Edited by pyscripter

Share this post


Link to post
3 hours ago, pyscripter said:

Any idea why the compiler does not free TerminateProc on its own Is this a compiler bug?

Answer myself.   I remember having seen these some time ago, when I have been bitten by this again:

 

delphi - Memory leaks happens in nested anonymous method - Stack Overflow

TURBU Tech » Blog Archive » How to leak a class you never defined (turbu-rpg.com)  (see Barry Kelly's comment).

 

Edited by pyscripter
  • Like 1

Share this post


Link to post

When I run that code in a vanilla VCL Forms Application in a ButtonClick event - nothing happens.

 

Either commenting out the last line or inserting a Sleep(100) before makes the ShowMessage appear.

 

The problem here is that the anon method captures the variable and not the value. Thus setting the value of TerminateProc to nil has influence of what is passed to TThread.Queue. It heavily depends on the timing of whether the Queue call comes first or the setting to nil.

 

Seems not to be a valid solution to avoid the leak.

  • Like 1
  • Thanks 1

Share this post


Link to post
19 minutes ago, Uwe Raabe said:

Seems not to be a valid solution to avoid the leak.

You are right.  I have removed the code from the post, so as not to confuse people.   The code at the first post works well.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×