我有一个第三方组件可以处理 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();
}
关于上面的几个问题:
AddFileToManipulate()
方法中的using
子句是否多余且不必要?- 我在对象的
Dispose()
方法中清理的东西是否正常? - 这是
MemoryStream
的“可接受”用法吗?我并没有预料到内存中会同时存储很多文件……总共可能有 1-10 页 PDF,每页大约 200KB。应用旨在在支持 ASP.NET 站点的服务器上运行。 - 有什么意见/建议吗?
感谢代码审查:)
最佳答案
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/