我们有一些(同步)电子邮件代码,该代码创建一个类,该类创建一个SmtpClient,然后发送电子邮件。 SmtpClient不被重用;但是,我们偶尔会出现以下异常:
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidOperationException: An asynchronous call is already in progress. It must be completed or canceled before you can call this method.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at EmailSender.SendMail(MailAddress fromMailAddress, string to, String subject, String body, Boolean highPriority) in ...\EmailSender.cs:line 143
代码如下:
// ...
var emailSender = new EmailSender();
emailSender.SendMail(toEmail, subject, body, true);
// emailSender not used past this point
// ...
public class EmailSender : IEmailSender
{
private readonly SmtpClient smtp;
public EmailSender()
{
smtp = new SmtpClient();
}
public void SendMail(MailAddress fromMailAddress, string to, string subject, string body, bool highPriority)
{
if (fromMailAddress == null)
throw new Exception();
if (to == null)
throw new ArgumentException("No valid recipients were supplied.", "to");
// Mail initialization
var mailMsg = new MailMessage
{
From = fromMailAddress,
Subject = subject,
Body = body,
IsBodyHtml = true,
Priority = (highPriority) ? MailPriority.High : MailPriority.Normal
};
mailMsg.To.Add(to);
smtp.Send(mailMsg);
}
}
最佳答案
您需要使用Dispose
,using
或通过为类EmailSender实现一次性模式来处置SmtpClient(此处更合适,因为您将SmtpClient的生存期与构造函数中EmailSender的生存期绑定(bind)在一起。)
那可以解决这个异常。
关于c# - 为什么在调用SmtpClient.Send时定期获取 "An asynchronous call is already in progress"?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16438190/