我的代码是否正确清理了其 List<MemoryStream>?

Bri*_*ian 4 c# dispose idisposable memorystream

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

这个第三方组件需要一个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
}
Run Code Online (Sandbox Code Playgroud)

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

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

针对以上的几个问题:

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

感谢您的代码审查:)

Sam*_*ron 5

AddFileToManipulate 让我害怕。

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

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

   pdfDocumentStreams.Add(new MemoryStream(pdfDocument));
Run Code Online (Sandbox Code Playgroud)

并在Dispose方法中将其处理掉。

此外,您还应该考虑实现一个终结器,以确保在有人忘记处置顶级对象的情况下处理掉一些东西。