【问题标题】:Timer elapsed event firing twice in C# command line program在 C# 命令行程序中,计时器经过事件触发两次
【发布时间】:2020-04-27 09:55:32
【问题描述】:

当程序启动时,我的计时器“Elapsed”事件会触发两次。 'Elapsed' 事件处理程序的唯一分配是在 'Main' 方法中。是不是我做错了什么?

//class level clock
public static System.Timers.Timer Clock;

static void Main(string[] args)
    {
       Clock = new System.Timers.Timer();
       Clock.Elapsed += new ElapsedEventHandler(Clock_Elapsed);
       Clock.AutoReset = false;
       Clock.Interval = timerInterval; //this needs to be in milliseconds!
       Clock.Enabled = true;

       //run infinite loop until q is pressed
       while (Console.Read() != 'q')
       {}
    }

static void Clock_Elapsed(object sender, ElapsedEventArgs e)
    {
    Clock.Stop();
    //do some stuff
    Clock.Start();             
     }

更新:

@fparadis2 提供的 AutoReset 修复了两次触发问题。基本问题是我的计时器间隔设置为 30 毫秒而不是 30000 毫秒(30 秒),因此事件是双触发的。

【问题讨论】:

标签: c# c#-4.0 command-line timer


【解决方案1】:

如果 timerInverval 足够小,则在您有机会停止时钟之前,可能会触发 Elapsed 事件两次。你应该这样做

Clock.AutoReset = false;

为了每次启动计时器时只收到一次通知。

Timer Class documentation中指定:

如果 Elapsed 事件的处理持续时间超过 Interval,则该事件可能会在另一个 ThreadPool 线程上再次引发。在这种情况下,事件处理程序应该是可重入的。

【讨论】:

    【解决方案2】:

    您也可以考虑查看pattern

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      相关资源
      最近更新 更多