How to call an asynchronous function on a non-asynchronous controller, to be clearer follows a situation:
I have a form that when saving it needs to save data in the database and simultaneously send an email notifying a user that such action has been taken on the system. But I want the sending of emails to be executed asynchronously from the method that writes the data.
I used as base an ex removed from the net, but in it only shows when the method is called directly and not when it is called another non-asynchronous method.
Code:
[HttpPost]
public ActionResult Index(DuvidasForm form)
{
if (!ModelState.IsValid)
return View(form);
var duvida = new Duvida
{
nome_envio = form.nome_envio,
email_envio = form.email_envio,
assunto_envio = form.assunto_envio,
msg_envio = form.msg_envio,
data_envio = DateTime.Now,
cursoid = form.cursoid,
temaid = form.temaid,
respondida = false
};
EnviarEmail(form.email_envio, form.assunto_envio, form.msg_envio);
db.Duvida.Add(duvida);
db.SaveChanges();
return PartialView("_NotificacaoEmail");
}
public async Task EnviarEmail(string toEmailAddress, string emailSubject, string emailMessage)
{
var smtp = new SmtpClient();
var message = new MailMessage();
message.To.Add(toEmailAddress);
message.Subject = emailSubject;
message.Body = emailMessage;
using (var smtpClient = new SmtpClient())
{
await smtpClient.SendMailAsync(message);
}
}