C#Timer与服务中的线程

我有一个服务,每10秒就会访问一个数据库并获取数据(如果有的话)。 问题是处理这些数据最多可能需要30秒。 如果我使用10秒间隔的定时器,服务将获得两次相同的数据。

我想要实现的效果(仅用于可视化):

while(true) { if(Getnrofrows() > 0) do stuff else sleep for 10 sec } 

Ppl说Thread.Sleep在生产服务中是个坏主意,我该怎么做定时器呢?

/麦克风

您是否尝试将Timer属性自动重置设置为false,并在刷新数据的过程结束时再次启用计时器

 using System; public class PortChat { public static System.Timers.Timer _timer; public static void Main() { _timer = new System.Timers.Timer(); _timer.AutoReset = false; _timer.Interval = 100; _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); _timer.Enabled = true; Console.ReadKey(); } static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { //Do database refresh _timer.Enabled = true; } } 

我没有看到使用Sleep的任何问题,除了你可能最终得到丑陋的代码。

回答你的问题:

 public class MyTest { System.Threading.Timer _timer; public MyTest() { _timer = new Timer(WorkMethod, 15000, 15000); } public void WorkMethod() { _timer.Change(Timeout.Infinite, Timeout.Infinite); // suspend timer // do work _timer.Change(15000, 15000); //resume } } 

这种方法没有错。 hibernate线程不消耗任何CPU周期。

如果你需要每隔X秒做一些事情,那么计时器就是你要走的路。 另一方面,如果要暂停X秒,则Thread.Sleep是合适的。

Thread.Sleep本身在一个服务中并不坏,只是你需要响应服务命令,所以你的工作线程不应该睡一小时,而是需要在很短的时间内睡觉,然后醒来并监听服务的服务控制器部分是否因某种原因告诉它停止。

您希望这样做,以便如果管理员告诉您的服务停止,它将足够快地停止,以便它不会收到任何超时消息,其中管理员无法确定您的服务是否已停止并且可以安全地重新启动机器或类似的。