4
How to make the call of an asynchronous function on a non-asynchronous controller, to be clearer follows a situation:
I have a form that when saving it needs to store data in the database and simultaneously send an email notifying a user that such action has been done in the system. But I want the sending of email to be executed asynchronous of the method that saves the data.
I have used as a basis an ex taken from the net, but in it 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);
}
}
But is there any reason why Action isn’t asynchronous? And your question is how to perform the tasks in parallel (each in a thread, to be executed "at the same time") or to execute the task as async, not to lock the Thread while running the upload?
– Diego Jeronymo
@Diegojeronymo Exactly this second option. Because when the user clicks on the Submit button of the form, it gives a delay, because currently the sending of email is not asynchronous.
– Matheus Silva