我正在使用流创建一个XmlDocument,并在XmlDocument中做一些更改,然后将XmlDocument保存到流本身。
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileStream);
////
////
////
xmlDocument.Save(fileStream);
//how to dispose the created XmlDocument object.
现在,我如何销毁XmlDocument对象?
发布于 2017-02-14 22:09:43
首先,您不应该像这样重用流。您真的想让外部资源长时间开放吗?在重新保存xml之前,您会先查找流吗?如果流比以前短,您会在保存后将其截断吗?
如果出于某种合理的原因,答案是正确的,那么将您的XML操纵器类设置为可处理:
public class MyXmlManipulator : IDisposable
{
private FileStream fileStream;
// ...
public void ManipulateXml()
{
// your original codes here...
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyXmlManipulator()
{
Dispose(false);
}
protected virtual Dispose(bool disposing)
{
fileStream.Close();
// etc...
}
}
但基本上我会说,不要保留对文件流的长期引用,并像这样重复使用它。相反,只在本地使用streams,并尽快处理它们。在这里,您全局可能只需要一个文件名。
public class MyXmlManipulator
{
private string fileName;
// ...
public void ManipulateXml()
{
XmlDocument xmlDocument = new XmlDocument();
using (var fs = new FileStream(fileName, FileMode.Open)
{
xmlDocument.Load(fs);
}
// ...
// FileMode.Create will overwrite the file. No seek and truncate is needed.
using (var fs = new FileStream(fileName, FileMode.Create)
{
xmlDocument.Save(fs);
}
}
}
发布于 2017-02-14 21:14:21
XmlDocument
类不实现IDisposable
,因此无法强制它随意释放其资源。如果需要释放内存,唯一的方法就是使用xmlDocument = null;
,垃圾收集将处理剩下的部分。
发布于 2017-02-14 21:13:32
无法释放XmlDocument,因为它不实现IDisposable。真正的问题是,为什么要销毁对象?
如果你不保留对对象的引用,垃圾回收器就会把它去掉。
如果你想让这个过程更快,你唯一能做的就是按照Fildor所说的去做,将对象设置为null
https://stackoverflow.com/questions/42226993
复制相似问题