c# - 我的代码是否正确清理了它的 List<MemoryStream>?

标签 c# dispose idisposable memorystream

我有一个第三方组件可以处理 PDF 文件。每当我需要执行操作时,我都会从文档存储(数据库、SharePoint、文件系统等)中检索 PDF 文档。为了使事情保持一致,我将 PDF 文档作为 byte[] 传递。

这个第 3 方组件需要一个 MemoryStream[](MemoryStream 数组)作为我需要使用的主要方法之一的参数。

我正在尝试将此功能包装在我自己的组件中,以便我可以在我的应用程序中的多个区域使用此功能。我基本上想出了以下内容:

public class PdfDocumentManipulator : IDisposable
{
   List<MemoryStream> pdfDocumentStreams = new List<MemoryStream>();

   public void AddFileToManipulate(byte[] pdfDocument)
   {
      using (MemoryStream stream = new MemoryStream(pdfDocument))
      {
         pdfDocumentStreams.Add(stream);
      }
   }

   public byte[] ManipulatePdfDocuments()
   {
      byte[] outputBytes = null;

      using (MemoryStream outputStream = new MemoryStream())
      {
           ThirdPartyComponent component = new ThirdPartyComponent();
           component.Manipuate(this.pdfDocumentStreams.ToArray(), outputStream);

           //move to begining
           outputStream.Seek(0, SeekOrigin.Begin);

           //convert the memory stream to a byte array
           outputBytes = outputStream.ToArray();
      }

      return outputBytes;
   }

   #region IDisposable Members
   public void Dispose()
   {
       for (int i = this.pdfDocumentStreams.Count - 1; i >= 0; i--)
       {
          MemoryStream stream = this.pdfDocumentStreams[i];
          this.pdfDocumentStreams.RemoveAt(i);
          stream.Dispose();
       }
   }
   #endregion
}

我的“包装器”的调用代码如下所示:

    byte[] manipulatedResult = null;
    using (PdfDocumentManipulator manipulator = new PdfDocumentManipulator())
    {
        manipulator.AddFileToManipulate(file1bytes);
        manipulator.AddFileToManipulate(file2bytes);
        manipulatedResult = manipulator.Manipulate();
    }

关于上面的几个问题:

  1. AddFileToManipulate() 方法中的 using 子句是否多余且不必要?
  2. 我在对象的 Dispose() 方法中清理的东西是否正常?
  3. 这是 MemoryStream 的“可接受”用法吗?我并没有预料到内存中会同时存储很多文件……总共可能有 1-10 页 PDF,每页大约 200KB。应用旨在在支持 ASP.NET 站点的服务器上运行。
  4. 有什么意见/建议吗?

感谢代码审查:)

最佳答案

AddFileToManipulate 吓到我了。

   public void AddFileToManipulate(byte[] pdfDocument)
   {
      using (MemoryStream stream = new MemoryStream(pdfDocument))
      {
         pdfDocumentStreams.Add(stream);
      }
   }

此代码将已处置的流添加到您的 pdfDocumentStream 列表中。相反,您应该使用以下方法简单地添加流:

   pdfDocumentStreams.Add(new MemoryStream(pdfDocument));

并在 Dispose 方法中处理它。

此外,您还应该考虑实现终结器,以确保在有人忘记处置顶级对象时处置掉东西。

关于c# - 我的代码是否正确清理了它的 List<MemoryStream>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/660801/

相关文章:

c# - 按位或 | 是什么意思运营商呢?

c# - Linq 查询帮助

.net - 来自核心 .NET 代码的 ObjectDisposedException

c# - 如何找到最少数量的公共(public)集

c# - C#/.NET 中的仅命名空间类可见性?

c# - 为什么我的 C# 表单在显示时关闭?

user-controls - 在 C# 中正确处理用户控件和子控件

c# - 在 C# 中处理对象

c# - Dispose() 方法中 GC.SuppressFinalize(this) 的目的是什么?

c# - 如果实例已被处置,则在不调用 EndXXX 的情况下调用 BeginXXX 是否安全