Question

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

Was it helpful?

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.

OTHER TIPS

I don't know Delphi but I've worked with IHTMLDocument in C++. I believe you need to call the Release() method. I also know it uses BSTR for strings so that might be another place to look for memory not being released.

Have you tried Navigate('about:blank'); before freeing? This should already free some memory. I also think the internals from WebBrower (which are roughly the same internals as Internet Explorer), keep a lot of things in memory, just to serve the history and cache to any other TWebBrowser (or IWebBrowser2 to be more specific) that may exist in this session of the executable, even in the (near) future.

With a bit of luck (and if you are using Navigate or Navigate2), you could change this if you call with flags like navNoHistory, navNoWriteToCache and perhaps others.

This problem is plaguing TWebbrowser users for ages and there is no solution so far ; the only way to release the memory used by TWebbrowser is to close your app and open it again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top