我需要在我的 ASP.NET 应用程序中定期执行某个任务,所以这样做:
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
}
}
}
这种方法好吗?
我看到一个关于该网站上的徽章授予的博客是使用 asp.net 缓存 hack 完成的:https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/ https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
您可以使用Timer http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx像这样的任务类。我在我自己的 ASP.NET 聊天模块中使用此类来在过期时间后关闭房间,并且效果很好。
我认为,这是比使用 Thread.Sleep 更好的方法 https://stackoverflow.com/questions/391621/compare-using-thread-sleep-and-timer-for-delayed-execution
下面的示例代码:
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();
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)