Asynchronous module or handler completed while asynchronous operation was pending

Asked

Viewed 1,338 times

1

I am trying to send an email asynchronously, without waiting for the return. However when I do not use the await I get an exception in return for action. inserir a descrição da imagem aqui

Code:

public Task MissaoAvaliada(string usuario, string destinatario)
{
    _email.From = new MailAddress("[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);
}

1 answer

3


The method SendMailAsync is still running asynchronously when the method RedirectToAction is executed, causing the code to go outside the scope of Action Avaliar. The problem is that asynchronous Action Avaliar is being abandoned while an asynchronous method (SendMailAsync) is still running and the variable teste is awaiting 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 so that the method is executed so that it is not necessary to wait for it, remove the variable teste and use this method:

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

I’m not sure, but maybe just remove the variable testecan resolve this error as the scope will no longer depend on the result, but I prefer the "fire and Forget approach".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.