C#:与XML.load的close方法(文件) [英] C# : the close method of Xml.Load(file)
问题描述
我写了使用的XmlDocument
对象加载XML文档,这样才能算它的节点一些代码。这里是方法:
I have written some code that loads an XML document using an XmlDocument
object so as to count it's nodes. Here is the method:
XmlDocument xml = new XmlDocument();
xml.Load(textBox1.Text);
XmlNodeList nodes = xml.SelectNodes("//File");
foreach (XmlNode node in nodes)
{
number_of_childs++;
}
这是我现在面临的问题是,导入大量文件时,它需要像RAM 700MB。如果我再尝试做对文件中的一些操作,甚至可以从中读取在的ListView
来显示其数据,应用程序需要像2GB的RAM。所以,我想知道,有没有关闭的XmlDocument
并释放其内存,释放内存的方法。它就像它忘记从内存中删除的内容。
The problem that I am facing is, when importing a large file, it takes like 700MB of RAM. If I then try to do some operation on the file, or even read from it to display its data in a ListView
, the application takes like 2GB of RAM. So, I was wondering, is there a method that closes the XmlDocument
and frees its memory, releasing the RAM. It is like it's forgetting to remove its content from memory.
推荐答案
没有。在的XmlDocument
类未实现的IDisposable
,所以没有办法,迫使它随心所欲地释放它的资源。如果你真的需要立即释放由的XmlDocument
使用的内存,这样做,是做以下的唯一方法:
No. The XmlDocument
class does not implement IDisposable
, so there is no way to force it to release it's resources at will. If you really need to immediately free the memory used by XmlDocument
, the only way to do that would be to do the following:
nodes = null;
xml = null;
GC.Collect();
垃圾收集器工作在一个单独的线程,因此它可能仍不会立即发生。要强制垃圾收集同步发生,你的代码继续执行之前,你还必须调用 WaitForPendingFinalizers
,因为这样的:
nodes = null;
xml = null;
GC.Collect();
GC.WaitForPendingFinalizers();
的XmlDocument
总是加载整个文档到内存立刻。如果你只是想通过节点的文档作为流中的迭代,每次只装了一下,那就是的XmlReader
类是什么。但是,你失去了很多功能的方式。举例来说,有没有办法通过XPath的选择节点,如你在哪里在你的例子做。随着的XmlReader
,你必须写你自己的逻辑来确定你在哪里,是否符合你在找什么在文档中。
XmlDocument
always loads the entire document into memory at once. If you simply want to iterate through the nodes in the document as a stream, only loading a bit at a time, that is what the XmlReader
class is for. However, you lose a lot of functionality that way. For instance, there is no way to select nodes via XPath, as you where doing in your example. With XmlReader
, you have to write your own logic to determine where in the document you are and whether that matches what you are looking for.
这篇关于C#:与XML.load的close方法(文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!