Asynchronous module or handler completed while asynchronous operation was pending

2

I'm trying to send an email asynchronously, without having to wait for the return. But when I do not use await I get an exception on return to action .

Code:

publicTaskMissaoAvaliada(stringusuario,stringdestinatario){_email.From=newMailAddress("[email protected]");
    _email.To.Add(destinatario);
    _email.Subject = "Email";
    _email.Body = string.Format($"Aqui vai o texto");
    return _cliente.SendMailAsync(_email);
}

Action:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Avaliar(RespostaViewModel viewModel)
{
     Resposta resposta = Mapper.Map<Resposta>(viewModel);
     Task teste;
     if (_respostaService.Update(resposta))
     {
         teste = _emailService.MissaoAvaliada("Leonardo", "meuemail");
         return RedirectToAction("Action", "controller");
     }
     else
         return View(viewModel);
}
    
asked by anonymous 30.08.2017 / 02:58

1 answer

2

The SendMailAsync method is still running asynchronously when the RedirectToAction method is executed, causing the code to exit the scope of Action Avaliar . The problem is that asynchronous Action Avaliar is being dropped while an asynchronous ( SendMailAsync ) method is still running and the teste variable is waiting for the result ( Task ) of this method.

Use the keywork await :

teste = await _emailService.MissaoAvaliada("Leonardo", "meuemail");

Or if you want to use the "fire and forget" concept for the method to run so that it is not necessary to wait for it, remove the teste variable and use this method:

Task.Factory.StartNew(() => _emailService.MissaoAvaliada("Leonardo", "meuemail"));

I'm not sure, but maybe just removing the teste variable can solve this error, because the scope will no longer depend on the result, but I prefer the approach "fire and forget".

    
30.08.2017 / 20:25