保存一个特定的计时器刻度

本文关键字:计时器 一个 保存 | 更新日期: 2023-09-27 18:04:02

我在Winforms (c#)中创建了一个游戏,我已经制作了一个计时器来跟踪正在进行的时间,计时器在游戏停止时停止。但是我还没有成功地节省时间计时器显示当游戏停止和发布它。

这就是我如何建立定时器功能。

private Timer timers;
public event EventHandler Tick;
StartGame()
{
  ...
  timers = new Timer();
  timers.Interval = 1000;
  timers.Tick += new EventHandler(TimerTick);
  timers.Enabled = true;
}
private void TimerTick(object sender, EventArgs e) 
{
  Time++;
  OnTick();
}
protected void OnTick() 
{
   if (Tick != null) 
   {
      Tick(this, new EventArgs());
   }     
}

保存一个特定的计时器刻度

不要使用计时器来测量时间——计时器从来都不准确,它们应该用来触发事件,仅此而已。特别是System.Windows.Forms.Timer,它运行在GUI线程中,可能会被其他消息阻塞。

根据你的问题,你想追踪游戏时间。我是这样做的:

private Stopwatch _sw = new Stopwatch();
public void StartOrResumeGame() {
    _sw.Start();
}
public void StopOrPauseGame() {
    _sw.Stop();
    _gameTimeMessage = String.Format("You have been playing for {0} seconds.", _sw.TotalSeconds);
}