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?
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. 🙂