gpt4 book ai didi

c# - 使用 Asp.Net 发送 Async 电子邮件但 Page 仍在等待?

转载 作者:行者123 更新时间:2023-11-30 12:34:54 25 4
gpt4 key购买 nike

我不希望用户等待页面完成发送过程,所以我想到了在 ASP.NET 3.5 中使用 SendAsync。但是调试后发现主线程还在等待。

Main: Call send email function...mailSend: Configuring....mailSend: setting up incorrect port....mailSend: Attempt now to send....mailSend: End of LineMain: Email Function call finish.Main: Proccess Complete!mailComp: Sending of mail failed, will try again in 5 seconds...mailComp: Retrying...mailComp: Send successful!mailComp: End of Line

现在我放置了不正确的端口设置,所以第一封电子邮件失败,并测试第二次是否会成功。即使使用了正确的端口,页面仍然在等待。只有在 mailComp 函数完成后,页面才最终发布。这是对 SendAsyn 的一些限制吗?

还有一些代码,不确定这是否有用。

    protected void btnReset_Click(object sender, EventArgs e)    {        try        {            DataContext db = new DataContext();            var query = from u in db.Fish                        where u.Username == txtUsername.Text & u.Email == txtEmail.Text                        select new { u.Username, u.Email };            if (query.Count() != 0)            {                User user = new User();                String token = user.requestPasswordReset(txtUsername.Text);                String URL = Request.Url.AbsoluteUri.ToString() + "?token=" + token;                String body = "Reseting you password if you \n" + URL + "\n \n ";                Untilty.SendEmail(txtEmail.Text, "Reseting Password", body);                litTitle.Text = "Message was sent!";                litInfo.Text = "Please check your email in a few minuets for further instruction.";                viewMode(false, false);            }            else            {                litCannotFindUserWithEmail.Visible = true;            }        }        catch (Exception ex)        {            Debug.Write("Main: Exception: " + ex.ToString());            litInfo.Text = "We are currently having some technically difficulty. Please try  again in a few minuets. If you are still having issue call us at 905344525";        }    }///public static class Utility///    public static void SendEmail(string recipient, string subject, string body)    {        MailMessage message = new MailMessage();        message.To.Add(new MailAddress(recipient));        message.From = new MailAddress(fromaddress, "Basadur Profile Website");        message.Subject = subject;        message.Body = body;        Send(message);    }    private static void Send(MailMessage msg)    {        SmtpClient smtp = new SmtpClient();        smtp.Host = "smtp.gmail.com";        smtp.Credentials = new System.Net.NetworkCredential(fromaddress, mailpassword);        smtp.EnableSsl = true;        Debug.WriteLine("mailSend: setting up incorrect port....");        smtp.Port = 5872; //incorrect port        smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted);        smtp.SendAsync(msg, msg);    }    static void smtp_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)    {        var msg = (MailMessage)e.UserState;        if (e.Error != null)        {            System.Threading.Thread.Sleep(1000 * 5);            try            {                SmtpClient smtp = new SmtpClient();                smtp.Host = "smtp.gmail.com";                smtp.Credentials = new System.Net.NetworkCredential(fromaddress, mailpassword);                smtp.EnableSsl = true;                smtp.Port = 587;                smtp.Send(msg);             }            catch (Exception ex)            {                Debug.WriteLine("mailComp: Failed for the second time giving up.");            }        }    }

最佳答案

在 .NET 4.5.2 中,添加了一种在后台调度任务的方法,独立于任何请求:HostingEnvironment.QueueBackgroundWorkItem() .

HostingEnvironment.QueueBackgroundWorkItem() 位于 System.Web.Hosting 命名空间中。

文档中的备注是这样说的:

Differs from a normal ThreadPool work item in that ASP.NET can keep track of how many work items registered through this API are currently running, and the ASP.NET runtime will try to delay AppDomain shutdown until these work items have finished executing.

意思是,您可以以即发即弃的方式启动任务,更有信心在应用域回收时任务不会被终止。

用法如下:

HostingEnvironment.QueueBackgroundWorkItem(cancellationToken =>
{
try
{
// do work....
}
catch(Exception)
{
//make sure nothing can throw in here
}
});

关于c# - 使用 Asp.Net 发送 Async 电子邮件但 Page 仍在等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6522720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com