SendMailAsync :异步模块或处理程序已完成,而异步操作仍未决

SendMailAsync : An asynchronous module or handler completed while an asynchronous operation was still pending

使用 SendMailAsync 时出现以下错误:

An asynchronous module or handler completed while an asynchronous operation was still pending

我的代码:

public static async Task SendEmail(MessageContent messageContent, string emailBody)
{
   SmtpClient smtpClientNoSend = new SmtpClient();
   await smtpClientNoSend.SendMailAsync(mailMessage);
}

来自控制器的调用:

public async System.Threading.Tasks.Task<ActionResult> Register()
{
   await SendEmail();
}

private void SendEmail()
{
  SMTPEmail.SendEmail(msg, output.ToString());
  return null;
}

您的通话层次结构已损坏。你不应该使用 async void,它只是用于事件处理程序,而是使用 async Task

public static Task SendEmailAsync(MessageContent messageContent, string emailBody)
{
   SmtpClient smtpClientNoSend = new SmtpClient();
   return smtpClientNoSend.SendMailAsync(mailMessage);
}

public async Task<ActionResult> Register()
{
   await SendEmailAsync();
}

private Task SendEmailAsync()
{
   return SMTPEmail.SendEmailAsync(msg, output.ToString());
}

旁注 - 我不确定为什么你有这么多 SendMail 方法,你可以将它们缩小到单个方法调用。