XMLDocument 处理 - 为什么它不支持 IDisposable?
XMLDocument 类似乎是支持 IDisposable 的理想候选者,因为……
- 它可能会保存大量数据。
- 它的 a 代表一个可能复杂的数据模型。
这将允许您在 using { ... } 语句中使用它,并且它会在使用后立即被垃圾收集。
但它似乎并不支持它。
在这种情况下,最好的处理方法是什么?
或者它不需要支持 IDisposable - 我想你可以在完成后将其引用设置为 null 吗?
或者这里的关键区别在于它不占用外部资源(例如数据库连接或外部文件),因此不需要 IDispoable“支持”?
The XMLDocument class would seem like an ideal candidate for supporting IDisposable because...
- it could potentially hold a lot of data.
- its a represents a possibly complex model of data.
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"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,它会在使用后立即处置,而不是垃圾收集。处置和垃圾收集不是一回事,尽管它们可能看起来很相似。
Dispose
旨在释放非托管资源,例如数据库连接、文件句柄、非托管内存等。垃圾收集会回收未使用的托管内存。对于
XmlDocument
,当不再有对它的引用时,它就符合垃圾回收的条件,并且它使用的内存将在需要时被回收。因此,您只需释放对XmlDocument
的所有引用并等待 GC 完成其工作即可。请注意,您可以强制进行GC循环,但您可能不应该:GC是一项昂贵的操作,系统比您更清楚何时是执行此操作的正确时间。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 theXmlDocument
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.是的,你说到点子上了。它使用的唯一资源是内存(可能有大量对象来表示 XML 文档),并且我们有一个完美的 cromulent 工具来管理 .net 中的内存。即垃圾收集器。
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.