I need to perform periodically a certain task in my asp.net app so did like this:
protected void Application_Start()
{
Worker.Start();
}
...
public static class Worker
{
public static void Start()
{
ThreadPool.QueueUserWorkItem(o => Work());
}
public static void Work()
{
while (true)
{
Thread.Sleep(1200000);
//do stuff
}
}
}
is this approach good ?
I saw a blog about the badge awarding on this site is done using an asp.net cache hack:
http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
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();
}
}
}
}
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.
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