我在尝试发送电子邮件异步时遇到了问题,我发现 Stackoverflow 上没有帖子,但没有一个有用。我有以下代码块
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
var mailMessage = new MailMessage
("me@example.com", message.Destination, message.Subject, message.Body);
mailMessage.IsBodyHtml = true;
var client = new SmtpClient();
client.SendCompleted += (s, e) => client.Dispose();
client.SendAsync(mailMessage,null);
return Task.FromResult(0);
}
}
我收到一封电子邮件,但在运行这段代码时出现异常
an asynchronous module or handler completed while an asynchronous operation was still pending.
有什么建议吗?
最佳答案
使用SendMailAsync
而不是 SendAsync
:
public class EmailService : IIdentityMessageService
{
public async Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
var mailMessage = new MailMessage
("me@example.com", message.Destination, message.Subject, message.Body);
mailMessage.IsBodyHtml = true;
using(var client = new SmtpClient())
{
await client.SendMailAsync(mailMessage);
}
}
}
关于c# - 如何发送邮件异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23725829/