【问题标题】:Sending email asynchronously and disposing异步发送电子邮件和处理
【发布时间】:2017-07-13 03:52:23
【问题描述】:

如果我将mail.Dispose() 放在末尾,SendMailAsync() 完成调用后是否会始终调用mail.Dispose()?例如,如果我调用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();
}

【问题讨论】:

  • 你可以用另一个包裹邮件。
  • 你不需要显式调用 Dispose,除非邮件有附件我在你的代码中没有看到。
  • @DanielA.White 我更新了将 MailMessage 放在 using 语句中的帖子,并将 SmtpClient 放入其中。那应该没问题吧?
  • @Win 知道了,我将允许附件,但这是我现在所拥有的
  • @Win 一般来说如果它实现了Dispose它应该被调用。在这种情况下,MailMessage 处理 other than attachments 的东西。

标签: c# asynchronous async-await smtpclient mailmessage


【解决方案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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-06
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多