每当我调用 smtpClient.SendAsync(...)
在我的 ASP.NET MVC 应用程序中,异步请求会自动取消,即使 SendAsyncCancel()
永远不会被调用。
同步.Send(...)
另一方面,请求通过就好了。
我的 EmailService
服务包装器使用 SmtpClient
处理发送异步电子邮件从我的 ASP.NET MVC 3 应用程序中。 StructureMap 将一个服务实例注入(inject)到每个 MVC Controller 中,它包装了一个新的 SmtpClient
using (...) { }
中的实例陈述。
这是我的EmailService.SendAsync
SmtpClient
的包装方法:
public void SendAsync(EmailMessage message)
{
try
{
using (var smtpClient = new SmtpClient(_cfg.Host, _cfg.Port)
{
EnableSsl = _cfg.EnableSsl,
Credentials = _credentials
})
{
smtpClient.SendCompleted += new SendCompletedEventHandler(Email_OnCompleted);
var mailMessage = new MailMessage(message.From, message.To)
{
Subject = message.Subject,
Body = message.Body
};
smtpClient.SendAsync(mailMessage, message);
_logger.Info(string.Format("Sending async email to {0} with subject [{1}]", message.To, message.Subject));
}
}
catch (Exception ex)
{
_logger.Error("Async email error: " + ex);
throw;
}
}
这是我的
Email_OnCompleted
代表:public void Email_OnCompleted(object sender, AsyncCompletedEventArgs e)
{
var mail = (EmailMessage)e.UserState;
if (e.Error != null)
{
_logger.Error(string.Format("Error sending email to {0} with subject [{1}]: {2}", mail.To, mail.Subject, e.Error));
}
else if (e.Cancelled)
{
_logger.Warn(string.Format("Cancelled email to {0} with subject [{1}].", mail.To, mail.Subject));
}
else
{
_logger.Info(string.Format("Sent email to {0} with subject [{1}].", mail.To, mail.Subject));
}
}
为什么异步邮件被取消了,而同步邮件却能顺利通过?这可能是一个处置问题吗?
最佳答案
这绝对是一个处置问题。当您处置客户端时,它会取消任何未完成的异步操作。
您应该在 Email_OnCompleted
中处理客户端.
关于处置地点的 SO 帖子:Dispose SmtpClient in SendComplete?
关于asp.net - 自动取消 SmtpClient.SendAsync 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8316785/