Search code examples
delphiwinapimemorycomtwebbrowser

How to release memory used by IHTMLDocument?


is there a way to release memory after using IHTMLDocument (IHTMLDocument2) ?

Currently I'm using EmptyWorkingSet function but I feel that it's not a good way to do it

EmptyWorkingSet(GetCurrentProcess);

Even freeing the TWebBrowser doesn't help; the problem seems to be in IHTMLDocument COM class which is not released from the memory. Is there a clear way to release it; something like Marshal.ReleaseComObject but available for Delphi ?

It's reproducable with less memory lose than with running JavaScript, but still. If you put two buttons on the top of the form and try the following code ...

uses MSHTML, SHDocVw;

type
  TForm1 = class(TForm)
  private
    WebBrowser: TWebBrowser;
    HTMLDocument: IHTMLDocument2;
  end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  WebBrowser := TWebBrowser.Create(nil);
  TWinControl(WebBrowser).Parent := Self;
  WebBrowser.SetBounds(8, 39, ClientWidth-16, ClientHeight-47);
  WebBrowser.Navigate('http://maps.google.com/');
  HTMLDocument := WebBrowser.Document as IHTMLDocument2;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  WebBrowser.Free;
  HTMLDocument := nil;
end;

You will see the memory lose after each WebBrowser freeing. When I run my JavaSrcipt it's much even more than 300 kB, it's about 1 MB and this may cause a memory leak in case I'm running this many times.

Thanks a lot


Solution

  • The COM classes should normally be freed when you release all references to them. Usually this can be done by assigning nil to all variables holding references to their interfaces.

    For immediate release of memory used by COM DLLs you can use CoFreeUnusedLibrariesEx.