1

I am using a custom text box (read only) that consist of 2 WebBrowser components. It's displaying text with complicated layout (Generating a html code was a simplest option to make such a text viewer).

I am also binding the mousedown event on all components:

foreach (HtmlElement html in webBrowser1.Document.All)
{
     html.MouseDown += new HtmlElementEventHandler(Scrollback_Clicked);
}

this happens after each time where I finish loading of html source. (this is irrelevant but it's the only customization of WebBrowser control I made, just in case it was the reason why it doesn't work)

However, after several hundreds of reloads the text box eats about 2GB of ram, I suspect it's a cache the browsercontrol has implemented, which stores all HtmlDocuments that were generated so far.

Is there a way to disable or flush the cache of WebBrowser control?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Petr
  • 13,747
  • 20
  • 89
  • 144

1 Answers1

2

First off, you're probably leaking event handlers, considering the way you're registering them and then failing to dispose them. That might cause a slight performance problem, but it obviously doesn't explain the consumption of an excessive 2 GB of RAM.

Anyway, the WebBrowser control is based on Internet Explorer, so it's possible it inherits a memory leak from there. You may also be onto something with the caching theory. There is a knowledge base article that discusses precisely this problem and how to solve it: How to clear the cache when your application hosts a WebBrowser control in Visual C# .NET.

Basically, it suggests that you manually flush the browser cache using the WinInet APIs. But that seems like a bit of a sledgehammer solution to me. It's solving a local problem using a global solution, which should raise a few red flags.

If I were you, I'd be rethinking my application's design so as to avoid this problem altogether. RichTextBox controls don't have any show-stopper memory leaks. :-)

Community
  • 1
  • 1
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • Hm, but I am using html.MouseDown -= new HtmlElementEventHandler(Scrollback_Clicked); before loading new document, so in fact these should get disposed. It's hard to track what's going on with memory in c# though – Petr Jul 26 '12 at 15:22
  • @Petr Oh, then you aren't leaking them. I assumed you'd forgotten to do that. Of course, as you mention, because garbage collection is non-deterministic, that doesn't guarantee that they get disposed right away, but you're doing it correctly and they won't leak. They'll get disposed when more memory is required, forcing a garbage collection. – Cody Gray - on strike Jul 26 '12 at 15:30