C#列表<流>处置/关闭 [英] C# List<Stream> dispose/close
问题描述
我正在设置订阅服务,以便按计划向我们公司的各个人员发送报告.我计划通过电子邮件发送报告,我使用的报告系统能够导出为 PDF 流(而不是编写临时文件).大多数人会收到不止一份报告,所以我试图将它们全部附加到一封电子邮件中,做一些类似的事情
I am setting up a subscription service to send reports to various people in our company on a schedule. I plan to email the reports, the reporting system I am using is able to export as PDF stream (rather than writing temp files). Most people will receive more than one report so I am trying to attach them all to one email doing something like
List<Stream> reports = new List<Stream>();
//looping code for each users set of reports
Stream stream = ReportSource.ReportDocument.ExportToStream(PortableDocFormat)
reports.Add(stream);
stream.Flush(); //unsure
stream.Close(); //unsure
//end looping code
SmtpClient smtpClient = new SmtpClient(host, port);
MailMessage message = new MailMessage(from, to, subject, body);
foreach (Stream report in reports)
{
message.Attachments.Add(new Attachment(report, "application/pdf"));
}
smtpClient.Send(message);
我不确定的是,我是否应该在将流添加到列表后立即刷新和关闭流,这样可以吗?或者我是否需要在之后循环列表以刷新和处理?我试图避免任何可能的内存泄漏.
What I am unsure about is should I be flushing and closing the stream just after adding it to the list will this be ok? Or do I need to loop the List afterwards to flush and dispose? I am trying to avoid any memory leak that is possible.
推荐答案
为什么不创建一个实现 IDisposable 的 StreamCollection 类:
Why not create a StreamCollection class that implements IDisposable:
public class StreamCollection : Collection<Stream>, IDisposable { }
在该类的 Dispose 方法中,您可以循环遍历所有流并正确关闭/处理每个流.然后你的代码看起来像:
In the Dispose method of that class, you could loop through all of the streams and properly Close/Dispose of each stream. Then your code would look like:
using (var reports = new StreamCollection())
{
//looping code for each users set of reports
reports.Add(ReportSource.ReportDocument.ExportToStream(PortableDocFormat));
//end looping codeSmtpClient
smtpClient = new SmtpClient(host, port);
MailMessage message = new MailMessage(from, to, subject, body);
foreach (Stream report in reports)
{
message.Attachments.Add(new Attachment(report, "application/pdf"));
}
smtpClient.Send(message);
}
这篇关于C#列表<流>处置/关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!