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?
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();
}
PS It was a quick fix, just to make the code work. Not necessarily correct from a design point of view. When System.Timers.Timer
s 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?
Make sure you only call
_timer.Tick += new EventHandler(_timer_Tick);
once.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.