计时器每秒滴答两次,然后在我重新使用它时滴答三次(我从不更改间隔)

Timer ticks twice per second then thrice when I reuse it (I never change the interval)

这应该是一个简单的游戏,每次您回答每个问题所用的时间超过允许的时间,您就会失去 1 条生命。我搜索了一个代码来设置我的计时器,找到了多种方法并最终使用了下面的方法。

起初我注意到 timer_Tick() 每秒运行 两次 而不是一次。所以我不得不将 ElapsedTime 增加 0.5f 而不是 1f 以获得正确的经过时间。 . 在我必须重新启动计时器之前(当我加载一个新问题时),它工作得很好。当我这样做时,timer_Tick() 每秒运行 three 次而不是两次。这意味着秒计数器减少 1.5f 而不是每秒 1f。我想知道是什么原因造成的,我该如何解决。提前致谢。

public void Start_timer(float Interval)
{
  ElapsedTime = 0f;
  timer.Tick += timer_Tick;
  timer.Interval = TimeSpan.FromSeconds(Interval);
  bool enabled = timer.IsEnabled;
  timer.Start();
}

void timer_Tick(object sender, object e)
{
    ElapsedTime += 0.5f; //I had to set this to 0.5f to get the correct reading as timer_Tick runs 2 times per second..
    TimeT.Text = "Time: " + Convert.ToString(QTime - ElapsedTime);
    if (ElapsedTime >= QTime && Lives == 0){
        timer.Stop();
        AnswerTB.IsEnabled = false;
        //GameOver
    }
    else if (ElapsedTime >= QTime && Lives != 0)
    {
        ElapsedTime = 0f;
        Lives--;
        LivesT.Text = "Lives: " + Convert.ToString(Lives);
        timer.Stop();
        LoadQuestion(); //This includes a Start_timer(1) call and I never change the 1 second interval.
    }
}

您每次启动计时器时都重新订阅 Tick 事件。如果您在计时器停止时不取消订阅,您最终会在每个滴答声中多次触发该事件。在创建计时器事件后,只需订阅一次 Tick 事件,然后就可以了。所以移动行

timer.Tick += timer_Tick;

到您创建计时器的代码部分。然后你应该能够停止和启动计时器而无需接收多个事件。