0

I have a small game with a timer, when a new match is started the timer must reset, but actually the new timer and the old overlap alternating. I don't understand why.

When a new game start this method it's called:

private void setGame()
{
   game = new Game();

   game.gameData.stopWatch = new StopWatch(timerLabel);
   game.gameData.scoreLabel = scoreLabel;
}

public StopWatch(Label timerLabel)
{
   this.timerLabel = timerLabel;

   _timer = new Timer();
   _timer.Interval = 1000;

   _timer.Tick += new EventHandler(_timer_Tick);
}

And then _timer_Tick it's called one time with the startData of actual match and another time with the startData of the old match. Why?

Vitto
  • 361
  • 3
  • 17

2 Answers2

1

When you create the new instance of StopWatch, the old one timer still active.

private void setGame()
{
    if (game != null)
        game.gameData.stopWatch.StopTimer();

    game = new Game();

    game.gameData.stopWatch = new StopWatch(timerLabel);
    game.gameData.scoreLabel = scoreLabel;
}

and add StopTimer function to StopWatch class:

public StopTimer()
{
    _timer.Stop();
}

P.S. It was a quick fix, just to make the code work. Not necessarily correct from a design point of view. When System.Timers.Timers are used, it might be better to implement Dispose pattern. See Is it necessary to dispose System.Timers.Timer if you use one in your application?

Community
  • 1
  • 1
AlexD
  • 32,156
  • 3
  • 71
  • 65
0

Make sure you only call

_timer.Tick += new EventHandler(_timer_Tick);

once.