这样做是否可以接受:
Attachment attachment = new Attachment(path, mediaType);
//Do other stuff...
using(attachment)
{
//Send email
}我通常直接在using语句中创建我的一次性操作,但在本例中,这有点复杂。
背景
我只是在一个遗留应用程序中遇到了一个bug,其中电子邮件附件没有释放文件句柄。因此,不能再修改该文件,因为它已经在使用中。
问题似乎是程序员忘记在附件上调用that ()。通常,这是一个很容易解决的问题,但在这种情况下,由于代码的结构,在创建附件时,我很难将附件直接放入使用中。
以上的选择是一个很好的妥协吗?
发布于 2017-10-24 21:18:31
真正的问题是,您不需要释放附件,因为MailMessage将在调用Dispose时和如果调用dispose时自动释放附件。
using(MailMessage message = ...)
{
}查看MailMessage类的内部,您将看到正在处理附件集合(附件):
protected virtual void Dispose(bool disposing)
{
if (disposing && !disposed)
{
disposed = true;
if(views != null){
views.Dispose();
}
if(attachments != null){
attachments.Dispose();
}
if(bodyView != null){
bodyView.Dispose();
}
}
}https://referencesource.microsoft.com/#System/net/System/Net/mail/MailMessage.cs
发布于 2017-10-24 21:09:11
如果在//Do other stuff期间发生异常,则不会释放对象。
您可以使用更传统的尝试/最后:
Attachment attachment;
try
{
attachment = new Attachment(path, mediaType);
//Do other stuff...
}
catch
{
//Handle or log exception
}
finally
{
if (attachment != null) attachment.Dispose();
}https://stackoverflow.com/questions/46920000
复制相似问题