We have some (synchronous) email code that creates a class that creates SmtpClient, and then sends the email. SmtpClient is not reused; however, from time to time we get the following exception:
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
The code is as follows:
// ... 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); } }
Danny tuppeny
source share