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

本文关键字:滴答 三次 两次 然后 计时器 | 更新日期: 2024-10-19 12:03:25

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

起初,我注意到timer_Tick()每秒运行两次,而不是一次。因此,我不得不将运行时间增加0.5f,而不是1fimer_Tick()每秒运行三次,而不是两次。。这意味着秒计数器从每秒1f减少到1.5f。我想知道是什么原因造成的,以及如何解决。提前谢谢。

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;

到代码中创建计时器的部分。然后,您应该能够在不接收多个事件的情况下停止和启动计时器。