huseyint
huseyint

Reputation: 15081

Should I dispose HtmlElement instances?

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?

Upvotes: 4

Views: 490

Answers (2)

TheDoctor
TheDoctor

Reputation: 1530

If you don't call the ReleaseComObject function, the objects will be released automatically by winforms. Msdn says it can be used to control the lifetime of an object, but it is not necessary.

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject.aspx

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941665

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.

Upvotes: 4

Related Questions