处理 MailMessage 附件

Disposing a MailMessage attachment

是否可以接受以下操作:

Attachment attachment = new Attachment(path, mediaType);

//Do other stuff...

using(attachment)
{
   //Send email
}

我通常直接在 using 语句中创建我的一次性用品,但在这种情况下有点复杂。

背景

我刚刚在旧版应用程序中遇到一个错误,其中电子邮件附件未释放文件句柄。因此,无法再修改该文件,因为它已在使用中。

看来问题是程序员忘记对附件调用 Dispose() 了。通常,这是一个很容易解决的问题,但在这种情况下,由于代码的结构,我无法在创建附件时直接将附件直接放入 using 中。

上面的替代方案是好的折衷方案吗?

如果 //Do other stuff 期间发生异常,您的对象将不会被释放。

您可以使用更传统的 try/finally:

Attachment attachment;
try
{
    attachment = new Attachment(path, mediaType);
    //Do other stuff...
}
catch
{
    //Handle or log exception
}
finally
{
    if (attachment != null) attachment.Dispose();
}

真正的问题是您不需要处理附件,因为当您在 MailMessage 上调用 Dispose 时 MailMessage 会自动处理附件。

using(MailMessage message = ...)
{

}

查看 MailMessage 的内部结构 class,您会看到正在处理一个附件集合:

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