在做asp.net计划的后台工作 [英] doing scheduled background work in asp.net
问题描述
我要在我的asp.net应用程序定期执行某项任务也一样是这样的:
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 ?
我看到一个有关这个网站的徽章授予博客使用asp.net缓存破解完成: <一href="http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/">http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
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/
推荐答案
您可以使用的定时器类这样的任务。我使用了经过一段过期时间关闭房间这个类在我自己的ASP.NET聊天模块,它工作正常。 我认为,这是<一href="http://stackoverflow.com/questions/391621/compare-using-thread-sleep-and-timer-for-delayed-execution">better方法比使用Thread.sleep代码
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
下面的例子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();
}
}
}
}
这篇关于在做asp.net计划的后台工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!