Should I dispose HtmlElement instances?

dispose, webbrowser-control, winforms

Solution

Manual memory management is always a bad idea, particularly so with COM objects. You can get an opinion about it from the experts, the blog post from the Visual Studio team brings the point home pretty well.

Just in case you still think it is a good idea, the Winforms team has already made the decision for you. The interface pointer wrapped by classes like HtmlDocument, HtmlElement, HtmlWindow, HtmlElementCollection etcetera is a private variable of the class. You simply can't get to it, not without breaking every rule in the book anyway.

It is not entirely impossible to have a problem, these wrapper class objects are pretty small so you may have a problem with the garbage collector not running often enough to ensure the underlying COM objects are released. GC.Collect() is the fallback for that. Only use it if necessary.

Problem

In WinForms, the `WebBrowser` control has a `Document` property in type `HtmlDocument`. The `HtmlDocument` instance has properties/methods like `Forms`, `Links`, `GetElementsByTagName()`, etc. that returns `HtmlElementCollection` instances. When I iterate over an `HtmlElementCollection` I am getting `HtmlElement` instances. These `HtmlElement` instances have `DomElement` properties which is a reference to the underlying COM object. My question is, should I call `Marshal.ReleaseComObject()` method on these `HtmlElement` instances or does WinForms manage the references internally?

Original source

Related problems