【问题标题】:Disposing of nested collection in C# [closed]在 C# 中处理嵌套集合 [关闭]
【发布时间】:2012-01-24 00:14:09
【问题描述】:

我有一组对象,每个对象都包含一组对象(从下面的代码中可以明显看出)。我想创建一个“处理”方法,删除所有附件,然后删除部分,这样我就可以删除相关文件。这些对象用于不同的地方,所以据我所知,“使用”方法是不合适的。以下失败(可以理解)因为集合已被修改。

// Find files and get names.
foreach (DocumentSection s in this.sections)
{
    foreach (EmailAttachment a in s.SectionAttachments)
    {
        // Get file location, then clear attachment to release file handle.
        filesToDelete.Add(a.TempAttachmentFileLoc);
        s.SectionAttachments.Remove(a);
        a = null;
    }
    this.sections.Remove(s);
    s = null;
}

我这样做的原因是因为我想在使用后删除临时文件(TempAttachmentFileLoc),但它正在使用中,目前无法删除。

【问题讨论】:

标签: c# .net dispose filehandle


【解决方案1】:

列举完清单后为什么不清除呢?

// Find files and get names.
foreach (DocumentSection s in this.sections)
{
    foreach (EmailAttachment a in s.SectionAttachments)
    {
        // Get file location, then clear attachment to release file handle.
        filesToDelete.Add(a.TempAttachmentFileLoc);
        //s.SectionAttachments.Remove(a);  // removed this!
        //a = null;
    }
    s.SessionAttachments.Clear();  // Added this
    //this.sections.Remove(s);  // Removed this
    //s = null;
}
this.sections.Clear();  // Added this

这应该做你正在尝试的。

【讨论】:

  • 想一想,因为你要清除整个sections 集合。不需要s.SessionAttachments.Clear()。假设集合和文档没有在其他任何地方引用,它们将在调用 this.sections.Clear() 后的下一次垃圾回收中被清理。
  • 谢谢吉姆。我已经这样做了,但仍然有奇怪的文件句柄问题。不过,感谢您的努力,我相信这可以毫无问题地进行处理。 :)
【解决方案2】:

您无需将列表中的项目删除到Dispose 他们。只需遍历您的列表,然后依次处理每个列表。如果要清空集合,请在循环完成后进行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 2020-10-22
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    相关资源
    最近更新 更多