Remotec
Remotec

Reputation: 10760

XMLDocument disposal - why doesnt it support IDisposable?

The XMLDocument class would seem like an ideal candidate for supporting IDisposable because...

This would allow you to use it inside a Using { ... } statement and it would be garbage collected immediately after use.

However it doesnt appear to support it.

In that case whats the best way to dispose of it?

Or doesnt it need to support IDisposable - I suppose you can just set its reference to null when you have finished with it?

Or is the key difference here that it doesnt tie up external resources such as DB connections or external files and hence doesnt require IDispoable "support"?

Upvotes: 2

Views: 3555

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292465

This would allow you to use it inside a Using { ... } statement and it would be garbage collected immediately after use.

No, it would be disposed immediately after use, not garbage collected. Disposal and garbage collection are not the same thing, although they might look similar. Dispose is designed to release unmanaged resources, such as DB connection, file handles, unmanaged memory, etc. Garbage collection reclaims unused managed memory.

In the case of XmlDocument, when no references to it remain, it becomes eligible for garbage collection, and the memory it uses will be reclaimed when needed. So you just have to release all references to the XmlDocument and wait for the GC to do its job. Note that you could force a GC cycle, but you probably shouldn't: GC is an expensive operation, and the system knows better than you when is the right time to do it.

Upvotes: 5

Binary Worrier
Binary Worrier

Reputation: 51711

Or is the key difference here that it doesnt tie up external resources such as DB connections or external files and hence doesnt require IDispoable "support"?

Yup, you've hit the nail on the head there. The only resource it uses is memory (granted potentially lots of objects to represent an XML document), and we've a perfectly cromulent facility for managing memory in .net. i.e. the garbage collector.

Upvotes: 3

Related Questions