簡體   English   中英

在ASP.net網站C#中自動執行操作

[英]do a operation automatically in ASP.net website C#

我有一段代碼,無論我查看的頁面如何,都需要在后台自動運行它們。 例如,如果我在主頁有關網站的頁面我想了一段代碼仍自動運行。 確切地說,我想每隔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);
    }
}

在DOT.NET世界中,異步調用可以通過許多方式來完成,例如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();
    }
}

希望這對您有幫助...

在您的情況下,您可以嘗試使用threding遵循以下代碼

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

希望這會幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM