如何在MVC中等待等待函数时返回视图

问题描述 投票:2回答:2

我使用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
                }
c# asp.net-mvc async-await
2个回答
2
投票

您可以将邮件代码包装在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"); 

0
投票

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"); 
© www.soinside.com 2019 - 2024. All rights reserved.