Form.Release + NIL

Holgerwa picture Holgerwa · Nov 8, 2008 · Viewed 7.6k times · Source

if Form.Release is called after using the form, it will free all related memory but not set the form variable to nil.

if not assigned (Form1) then
  begin
    Application.CreateForm(Tform1, Form1);
    try
      // Do something
    finally
      Form1.Release
    end;
  end;

To be able to call the same code again, Form1 would have to be set to nil at some point. From the description of Release I cannot do

Form1 := nil;

right after Release, because the Release procedure will return directly after being called and before the form is actually freed. I cannot detect when Form.Release is finished to set the form var to nil.

What is the best way to do this?

Answer

a.delphi.developer picture a.delphi.developer · Nov 8, 2008

Put the line

  Form1 := nil;  

just after the call to Release.

Release is just posting a CM_RELEASE message to the Form which allows the Form to finish what's in its queue (event handlers) before handling the CM_RELEASE message which means normally just calling Free.
So, after calling Release, you should not assume that the Form variable still points to a valid Form, thus putting nil into the variable.