在C#中,如果您尝试在上一个完成之前发送包含SendAsync
的电子邮件,则会引发此异常:
异步调用已在进行中。必须先完成或取消,然后才能调用此方法。
这很有意义,但我找不到像IsBusy
这样的属性来检查客户端是否已准备好接受新的发送请求。我可能只是尝试处理异常,但我想知道是否有更清洁的方法。
我正在尝试SendMailAsync
:
public async Task SendEmail(string address, string subject, string body, Attachment attachment)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(m_smtp.username);
mail.To.Add(address);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
if (attachment != null)
{
mail.Attachments.Add(attachment);
}
await m_smtpClient.SendMailAsync(mail);
Console.WriteLine("Send completed!");
}
这会引发以下异常(但调试器不会中断执行):
Exception thrown: 'System.Net.Mail.SmtpException' in mscorlib.dll
Failure sending mail.
System.NotSupportedException: Stream does not support reading.
at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult)
at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)
如果我仅使用SendMailAsync()
更改Send()
,则会成功发送电子邮件。