doing scheduled background work in asp.net

后端 未结 3 980
旧巷少年郎
旧巷少年郎 2021-01-17 06:18

I need to perform periodically a certain task in my asp.net app so did like this:

protected void Application_Start()
{
    Worker.Start();
}

...
 public sta         


        
相关标签:
3条回答
  • 2021-01-17 06:58

    Your method will work, but as Lucasus said, better approach will be using Timer class.

    Other than that if you own the computer where your site is running I would recommend using Windows service for your scheduling tasks. This approach will proove itself more beneficial than timers of any kind inside of asp.net infrastructure. That is because everything that is working inside asp.net is going to be managed by asp.net engine and it is not something you want. For example worker process can be recycled and at this moment your task will break.

    Detailed information about timers in windows services can be found here: Timers and windows services.

    Information about windows services can be found here: Windows services

    To hoock timer into windows service you need to create it at the start and handle events that it fires.

    0 讨论(0)
  • 2021-01-17 07:10

    You can use Timer class for task like this. I'm using this class in my own ASP.NET chat module for closing rooms after some expiration time and it works fine. And I think, it's better approach than using Thread.Sleep

    Below example code:

    using System;
    using System.IO;
    using System.Threading;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Worker.Start();
                Thread.Sleep(2000);
            }
    
            public static class Worker
            {
                private static Timer timer;
    
                public static void Start()
                {
                    //Work(new object());
                    int period = 1000;
                    timer = new Timer(new TimerCallback(Work), null, period, period);
                }
    
                public static void Work(object stateInfo)
                {
                    TextWriter tw = new StreamWriter(@"w:\date.txt");
    
                    // write a line of text to the file
                    tw.WriteLine(DateTime.Now);
    
                    // close the stream
                    tw.Close();
                }
    
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-17 07:19

    If you want do do a scheduled work, why not use Windows Task Scheduler ?

    Some info I found, may be useful: http://www.codeproject.com/KB/cs/tsnewlib.aspx

    Kris

    0 讨论(0)
提交回复
热议问题