Reputation: 1553
I work with await function for sending an email. Is there have any solutions how to display page or return view() while waiting for await function complete.
Here is my code:
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "[email protected]",
Password = "paswordEmail"
};
smtp.Credentials = credential;
smtp.Host = "smtp-mail.outlook.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message); //Here is my await function for sending an email
return RedirectToAction("ThankYou"); //This thank you page. I want to display this html page without waiting for await complete
}
Upvotes: 2
Views: 575
Reputation: 14846
ASP.NET has it's own facility to execute background work: HostingEnvironment.QueueBackgroundWorkItem Method.
Just post your work there:
HostingEnvironment.QueueBackgroundWorkItem(
async () =>
{
using (var smtp = new SmtpClient
{
Host = "smtp-mail.outlook.com",
Port = 587,
EnableSsl = true,
Credentials = new NetworkCredential
{
UserName = "[email protected]",
Password = "paswordEmail",
},
})
{
await smtp.SendMailAsync(message); //Here is my await function for sending an email
}
});
return RedirectToAction("ThankYou");
Upvotes: 1
Reputation: 247018
You can wrap the mail code in a Task.Run
and not await it.
Task.Run(async () => {
using (var smtp = new SmtpClient()) {
var credential = new NetworkCredential {
UserName = "[email protected]",
Password = "paswordEmail"
};
smtp.Credentials = credential;
smtp.Host = "smtp-mail.outlook.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message); //Here is my await function for sending an email
}
});
return RedirectToAction("ThankYou");
Upvotes: 2