我使用await函数发送电子邮件。是否有任何解决方案如何在等待等待功能完成时显示页面或返回视图()。
这是我的代码:
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
}
您可以将邮件代码包装在Task.Run
中,而不是等待它。
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");
ASP.NET有自己的工具来执行后台工作:HostingEnvironment.QueueBackgroundWorkItem Method。
只需在那里发布您的工作:
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");