c# - 如何在MVC中等待await函数时返回 View

标签 c# asp.net-mvc async-await

我使用等待函数来发送电子邮件。是否有任何解决方案如何在等待await函数完成时显示页面或返回view()。

这是我的代码:

 using (var smtp = new SmtpClient())
                {
                    var credential = new NetworkCredential
                    {
                        UserName = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="751018141c19351218141c195b161a18" rel="noreferrer noopener nofollow">[email protected]</a>",
                        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 = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f3fbf7fffad6f1fbf7fffab8f5f9fb" rel="noreferrer noopener nofollow">[email protected]</a>",
            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"); 

关于c# - 如何在MVC中等待await函数时返回 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54300604/

相关文章:

c# - Html.EditorFor 设置默认值

c# - 使用网络浏览器打印文档显示

c# - 异步 void lambda 表达式

javascript - useState 与异步函数返回 Promise {<pending>}

c# - 如何以编程方式隐藏键盘

c# - WCF net tcp 端口共享

c# - 如何使用对象的值反序列化对象

c# - 如何保存具有透明背景的 gif?

asp.net-mvc - 如何修复:Cannot perform runtime binding on a null reference

c# - 初始化 Xamarin.Forms 应用程序时找不到调用异步方法的方法