我使用等待功能来发送电子邮件。有什么解决方案,如何在等待功能完成时显示页面或返回view()。
这是我的代码:
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "email@gmail.com",
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
}
答案 0 :(得分:2)
您可以将邮件代码包装在Task.Run
中,而不必等待它。
Task.Run(async () => {
using (var smtp = new SmtpClient()) {
var credential = new NetworkCredential {
UserName = "email@gmail.com",
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");
答案 1 :(得分:0)
ASP.NET具有执行后台工作的专用工具:https://laravel.com/docs/5.7/queries#increment-and-decrement。
只需在此处发布您的作品即可
HostingEnvironment.QueueBackgroundWorkItem(
async () =>
{
using (var smtp = new SmtpClient
{
Host = "smtp-mail.outlook.com",
Port = 587,
EnableSsl = true,
Credentials = new NetworkCredential
{
UserName = "email@gmail.com",
Password = "paswordEmail",
},
})
{
await smtp.SendMailAsync(message); //Here is my await function for sending an email
}
});
return RedirectToAction("ThankYou");