Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

While using SendMailAsync I am getting the following error:

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

My code :

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

Call From Controller:

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

private void SendEmail()
{
  SMTPEmail.SendEmail(msg, output.ToString());
  return null;
}
like image 709
Bokambo Avatar asked May 18 '15 14:05

Bokambo


People also ask

How does async await work in Web API?

We add an async keyword to the method signature, modify the return type by using Task , and we use the await keyword when we call the GetAllCompanies awaitable method. The rest of the code – the mapping part, the logging part, and the return of the result – will be executed after the awaitable operation completes.


1 Answers

Your call hierarchy is broken. You shouldn't use async void, that is ment for event handlers only, use async Task instead:

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());
}

Side note - I'm not sure why you have so many SendMail methods, You could narrow them down to a single method call.

like image 154
Yuval Itzchakov Avatar answered Oct 04 '22 01:10

Yuval Itzchakov