My system (.Net 4.8) sends e-mail, and today we have await
before each call. It works fine but takes some seconds to send each e-mail, meanwhile user just keeps waiting.
Trying to speed up this proccess, we tried to apply _ =
to that line, but then eventually we got this error:
An asynchronous module or handler completed while an asynchronous operation was still pending
I've also tried this other approach Task.Run
but then SendEmailMessage
wouldn't even run.
After some research I've understood that ASP.NET doesn't work well under this circustances (reference: here and here). Since all request have being fulfilled there is no need to keep that process ongoing; so when the main process CreateNewProduct
finishes, SendEmailMessage
still is in progress but is also terminated.
I was wondering if there is a way to make .Net work with this situation. Maybe to create a new stack or something to process these async process? I did see some suggestions like to use RabbitMQ
but I wouldn't like to have additional services running.
public async Task<JsonResult> CreateNewProduct(string productID){
//Code here
//current approach (several e-mails)
await SendEmailMessage(messageBody1);
await SendEmailMessage(messageBody2);
await SendEmailMessage(messageBody3);
//new approach 1
_ = SendEmailMessage(messageBody1);
//new approach 2
Task.Run(() => SendEmailMessage(messageBody1));
return Json(new
{
success = true,
}, JsonRequestBehavior.AllowGet);
}
public async Task SendEmailMessage(string messageBody){
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) =>
{
Console.WriteLine(e);
return true;
};
await client.ConnectAsync(_SMTPserver, _SMTPport, true);
await client.AuthenticateAsync(_address, _password);
await client.SendAsync(messageBody);
client.Disconnect(true);
}
}