使用Disposables

时间:2017-07-17 08:08:54

标签: asp.net .net vb.net email smtpclient

最近经过一堆代码整理和“改进”的事情,我注意到这段代码用于发送电子邮件:

Dim SmtpServer As New SmtpClient() With {
    .Port = 25,
    .Host = Email.Hostname,
    .Credentials = New NetworkCredential() With {
        .UserName = Email.UserName,
        .Password = Email.Password      
    }
}

Dim mail As New MailMessage() With {
    .From = Email.Sender,
    .Subject = Email.Subject,
    .IsBodyHtml = True,
    .Body = Email.WrappedHtml
}
If Not Email.Attachments Is Nothing Then
    For Each a In Email.Attachments
        mail.Attachments.Add(a)
    Next
End If    
mail.To.Add(New MailAddress(Email.Recipient.Email, Email.Recipient.Name))
Call SmtpServer.Send(mail)

SmtpServer.Dispose()
mail.Dispose()
SmtpServer = Nothing
mail = Nothing

在该示例中,Email对象是包含基本电子邮件信息,收件人,发件人,附件等的类。

上面的代码完美无缺......

但是,我注意到SmtpServerMailMessage都是Disposable个对象,最好将它们包装在Using语句中,因此:

Using SmtpServer As New SmtpClient() With {
    .Port = 25,
    .Host = Email.Hostname,
    .Credentials = New NetworkCredential() With {
        .UserName = Email.UserName,
        .Password = Email.Password      
    }
    }

    Using mail As New MailMessage() With {
            .From = Email.Sender,
            .Subject = Email.Subject,
            .IsBodyHtml = True,
            .Body = Email.WrappedHtml
        }
        If Not Email.Attachments Is Nothing Then
            For Each a In Email.Attachments
                mail.Attachments.Add(a)
            Next
        End If    
        mail.To.Add(New MailAddress(Email.Recipient.Email, Email.Recipient.Name))
        Call SmtpServer.Send(mail)
    End Using
End Using

然而......当我这样做的时候,我会快速连续发送几封电子邮件:

  

System.Net.Mail.SmtpException:发送邮件失败。 ---> System.IO.IOException:无法从传输连接读取数据:net_io_connectionclosed。在System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(字节[]缓冲液,的Int32偏移的Int32读,布尔read430)在System.Net.Mail.SmtpReplyReaderFactory.Read430s(SmtpReplyReader呼叫者,布尔one430)在System.Net.Mail.SmtpReplyReaderFactory .Read430(SmtpReplyReader调用者)在System.Net.Mail.CheckCommand.Send(SmtpConnection conn,String& response)处于System.Net.Mail.MailCommand.Send(SmtpConnection conn,Byte []命令,MailAddress from,Boolean allowUnicode)at at System.Net.Mail.SmtpClient.Send(MailMessage消息)中的System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,MailAddressCollection recipients,String deliveryNotify,Boolean allowUnicode,SmtpFailedRecipientException& exception)

Using语句似乎导致连接过早关闭....

其他人对解决方案有类似的经验/提示吗?

我已经恢复了旧代码,但更好的做法是用using语句换行,对吗?

0 个答案:

没有答案