2017-02-22 100 views
1

如果我在末尾放mail.Dispose()mail.Dispose()总是在SendMailAsync()完成其呼叫后被调用?例如,如果我拨打Post()一千次,应在每封电子邮件发送后调用dispose。异步发送邮件并处理

这里是我的代码:

public async Task Post(NotificationData notification) 
{ 
    MailMessage mail = new MailMessage(); 
    mail.To.Add(new MailAddress(notification.Email)); 
    mail.Subject = notification.Subject; 
    mail.Body = notification.Body; 

    using (SmtpClient smtp = new SmtpClient()) 
    { 
     smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_SendCompleted); 
     await smtp.SendMailAsync(mail); 
    } 

    mail.Dispose(); 
} 
+3

你可以包装里边反邮件在另一个使用。 –

+0

您不需要明确地调用Dispose,除非邮件中包含附件*,而在附件*中我没有在您的代码中看到*。 – Win

+0

@ DanielA.White我更新了将MailMessage放入using语句并将SmtpClient放入其中的文章。所以这应该是正确的? –

回答

1
public async Task Post(NotificationData notification) 
{ 
    using (MailMessage mail = new MailMessage()) 
    { 
     mail.To.Add(new MailAddress(notification.Email)); 
     mail.Subject = notification.Subject; 
     mail.Body = notification.Body; 

     using (SmtpClient smtp = new SmtpClient()) 
     { 
      smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_SendCompleted); 
      await smtp.SendMailAsync(mail); 
     } 
    } 
}