doing scheduled background work in asp.net

后端 未结 3 1006
旧巷少年郎
旧巷少年郎 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 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();
                }
    
            }
        }
    }
    

提交回复
热议问题