在ASP.net网站c#中自动执行一个操作

本文关键字:操作 一个 执行 net ASP 网站 | 更新日期: 2023-09-27 18:14:21

我有一段代码,我需要在后台自动运行,无论我正在查看的页面。例如,如果我在主页关于网页的一个网站,我想要一段代码仍然自动运行。准确地说,我想每隔30分钟从我创建的电子邮件类中发送一封电子邮件通知。我知道类似的事情可以通过windows服务完成,但我希望代码在网站上。

public class Email
{
    string emailFrom = "senderemail@gmail.com";
    string password = "yourpassword";        
    string smtpServer = "smtp.gmail.com";
    int port = 587;
    public void sendEmail(string emailTo, string subject, string body)
    {
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress(emailFrom);
        msg.To.Add(emailTo);
        msg.Subject = subject;
        msg.Body = body;
        SmtpClient sc = new SmtpClient(smtpServer);
        sc.Port = port;
        sc.Credentials = new NetworkCredential(emailFrom, password);
        sc.EnableSsl = true;
        sc.Send(msg);
    }
}

在ASP.net网站c#中自动执行一个操作

In DOT。异步调用可以通过多种方式实现,如AJAX、AsyncHandlers等。

这里你可以使用"BackgroundWorker"

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += new DoWorkEventHandler(DoWork);
    worker.WorkerReportsProgress = false;
    worker.WorkerSupportsCancellation = true;
    worker.RunWorkerCompleted +=
           new RunWorkerCompletedEventHandler(WorkerCompleted);
    //Add this BackgroundWorker object instance to the cache (custom cache implementation)
    //so it can be cleared when the Application_End event fires.
    CacheManager.Add("BackgroundWorker", worker);
    // Calling the DoWork Method Asynchronously
    worker.RunWorkerAsync(); //we can also pass parameters to the async method....
}
private static void DoWork(object sender, DoWorkEventArgs e)
{
    // You code to send mail..
}
private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    if (worker != null)
    {
        // sleep for 30 minutes and again call DoWork to send mail.
        System.Threading.Thread.Sleep(3600000);
        worker.RunWorkerAsync();
    }
}
void Application_End(object sender, EventArgs e)
{
    //  Code that runs on application shutdown
    //If background worker process is running then clean up that object.
    if (CacheManager.IsExists("BackgroundWorker"))
    {
        BackgroundWorker worker = (BackgroundWorker)CacheManager.Get("BackgroundWorker");
        if (worker != null)
            worker.CancelAsync();
    }
}

在您的情况下,您可以尝试使用以下代码使用线程

var timer = new System.Threading.Timer((e) =>
{
    sendEmail(string emailTo, string subject, string body);   
}, null, 0, TimeSpan.FromMinutes(5).TotalMilliseconds);