【问题标题】:doing scheduled background work in asp.net在 asp.net 中进行预定的后台工作
【发布时间】:2011-10-04 08:44:43
【问题描述】:

我需要在我的 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 缓存破解完成的: https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/

【问题讨论】:

    标签: c# .net asp.net multithreading


    【解决方案1】:

    你可以使用Timer 类来完成这样的任务。我在我自己的 ASP.NET 聊天模块中使用这个类在一些过期时间后关闭房间,它工作正常。 我想,是better approach than using Thread.Sleep

    下面的示例代码:

    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();
                }
    
            }
        }
    }
    

    【讨论】:

    • 使用定时器我还需要ThreadPool.QueueUserWorkItem(o => Work()); 吗?不同的是我不再需要 while(true) Thread.sleep 了?
    • @Chuck,是的,你不需要这些东西。现在查看我的帖子,我编写的示例代码完全符合您的要求,但使用了 Timer 方法
    • @Chuck,Work 方法永远不会被执行,因为程序会立即退出。定时器对象被释放,定时器线程在程序退出后停止。我已经编辑了这个程序 - 在“Worker.Start()”之后添加了 Thread.Sleep(2000)。现在 Work 函数有足够的时间执行了。
    【解决方案2】:

    您的方法会起作用,但正如卢卡萨斯所说,更好的方法是使用Timer class

    除此之外,如果您拥有运行站点的计算机,我建议您使用 Windows 服务来执行计划任务。这种方法将证明自己比 asp.net 基础架构中的任何类型的计时器更有益。那是因为在 asp.net 中工作的所有东西都将由 asp.net 引擎管理,这不是你想要的。例如,工作进程可以回收,此时您的任务将中断。

    关于windows服务中定时器的详细信息可以在这里找到:Timers and windows services

    有关 Windows 服务的信息可以在这里找到:Windows services

    要将计时器连接到 Windows 服务中,您需要在启动时创建它并处理它触发的事件。

    【讨论】:

    • 使用定时器我还需要ThreadPool.QueueUserWorkItem(o => Work()); 吗?不同的是我不再需要 while(true) Thread.sleep 了?
    【解决方案3】:

    如果您想做有计划的工作,为什么不使用 Windows 任务计划程序?

    我找到的一些信息,可能有用:http://www.codeproject.com/KB/cs/tsnewlib.aspx

    克里斯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 2013-04-01
      • 2023-03-28
      相关资源
      最近更新 更多