【问题标题】:How to dispose XmlDocument如何处理 XmlDocument
【发布时间】:2017-02-14 13:06:46
【问题描述】:

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

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

////
////

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

现在如何销毁 XmlDocument 对象?

【问题讨论】:

  • xmlDocument = null; 但你也可以让它超出范围。 GC 将完成剩下的工作。
  • 'dispose'在C#中有特定的含义,与IDisposable接口有关。它主要用于处理非托管资源。但这里不是这种情况。只要不再引用您的 XmlDocument 实例,它就可以进行垃圾回收。

标签: c# .net xmldocument


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    XmlDocument 类没有实现IDisposable,所以没有办法强制它随意释放它的资源。如果您需要释放该内存,那么这样做的唯一方法是xmlDocument = null;,而垃圾收集将处理其余部分。

    【讨论】:

      【解决方案3】:

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

      我没有保留对垃圾收集器将删除它的对象的引用。

      如果你想让这个过程更快,你唯一能做的就是按照 Fildor 说的,将对象设置为 null

      【讨论】:

      • 上面不是有人说的吗。
      猜你喜欢
      • 2016-02-16
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多