如何处理XmlDocument

5

我正在使用流创建XmlDocument,并对XmlDocument进行一些更改,然后将XmlDocument保存到流本身中。

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileStream);

////
////

////  
xmlDocument.Save(fileStream);
//how to dispose the created XmlDocument object.

现在我该如何销毁XmlDocument对象?

xmlDocument = null; 但你也可以让它超出范围。垃圾回收器会处理剩下的部分。 - Fildor
“Dispose”在C#中有一个特定的含义,与“IDisposable”接口相关。它主要用于处理非托管资源。但这里并非如此。只要您的“XmlDocument”实例没有更多的引用,它就可以进行垃圾回收了。 - Pieter Witvoet
3个回答

5

XmlDocument类没有实现IDisposable接口,因此没有办法强制释放其资源。如果需要释放内存,则唯一的方法是xmlDocument = null;,垃圾回收器会处理剩余部分。


5

首先,您不应该像这样重复使用流。您真的想让外部资源长时间保持打开状态吗?在重新保存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...
    }
}

基本上,我建议不要保留一个长期引用到文件流并像那样重复使用它。相反,只在本地使用流,并尽快处置它们。在这里你可能只需要全局一个文件名。

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);
        }
    }
}

0

XmlDocument 无法被销毁,因为它未实现IDisposable。 真正的问题是为什么你想要销毁这个对象?

如果你没有保留该对象的引用,垃圾回收器将会处理它。

如果想让进程更快,唯一能做的就是像Fildor所说的那样设置对象为null


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接