pyscripter 694 Posted October 28, 2023 (edited) 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 October 28, 2023 by pyscripter Share this post Link to post
pyscripter 694 Posted October 28, 2023 (edited) 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 October 28, 2023 by pyscripter 1 Share this post Link to post
Uwe Raabe 2063 Posted October 28, 2023 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. 1 1 Share this post Link to post
pyscripter 694 Posted October 28, 2023 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