2

我在 Windows 服务中使用 system.timer 来运行通常超过计时器间隔的进程。我试图阻止计时器多次触发相同的代码,这是 system.timers 的一个已知问题。

我想要什么:计时器运行我的代码,但计时器“暂停”以等待代码完成,然后再恢复滴答声。

我有两个问题:

  1. system.timers 的工作方式是计时器将通过启动相同代码的新冗余线程来为您创建竞争条件,如果在计时器的时间间隔过去时尚未完成,则将它们堆积在您身上。

  2. 我会启动/停止计时器以防止这种情况发生,但是使用 System.Timers.Timer,一旦您停止计时器以完成处理,它就永远不会回来 - 我永远无法重新启动计时器已停止,它已被销毁并可能被收集。启用/禁用与启动/停止完全相同,结果相同。

如果在定时器的时间间隔过去时进程还没有完成,你到底如何让 system.timer 不启动相同代码的新冗余线程?显然,启动/停止(启用/禁用)计时器不是解决方案,因为它不起作用。

帮助!

4

2 回答 2

2

在需要启动计时器时启动它,然后启动另一个线程来完成工作,之后可以停止计时器。计时器不会关心线程是完成还是带着奖金跑掉了。使用任务并行库 (TPL) 以获得最有效的使用。

于 2015-08-28T22:41:28.877 回答
1

Timer 上的 Start 和 Stop 方法确实在 Windows 服务中工作。我有多个生产服务使用执行此操作的代码,但我的代码是用 C# 编写的。

但是,请确保您使用的是System.Timers.Timer不是Windows.Forms.Timer

这是我的服务外观的 C# / 伪代码的快速示例。

// this is the OnStart() event which fires when windows svc is started
private void OnStart()
{
    // start your timer here.
    MainTimer.Start();
}

private void ElapsedEventHandler()
{
      try
      { 
          // Stop the timer, first thing so the problem of another timer
          // entering this code does not occur
          MainTimer.Stop();

          //Do work here...   
      }
      catch (Exception ex)
      { 
          // if you need to handle any exceptions - write to log etc.
      }
      finally
      {
         MainTimer.Start();
         // finally clause always runs and will insure
         // your timer is always restarted.
      }
}
于 2015-08-28T22:54:39.367 回答