【问题标题】:C# Old timer overlap the newC# 旧计时器与新计时器重叠
【发布时间】:2014-08-08 15:08:25
【问题描述】:

我有一个带有计时器的小游戏,当新比赛开始时计时器必须重置,但实际上新计时器和旧计时器交替重叠。我不明白为什么。

当一个新游戏启动这个方法时,它被调用:

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);
}

然后_timer_Tick 被调用一次与实际匹配的startData 和另一次与旧匹配的startData。为什么?

【问题讨论】:

    标签: c# timer overlap


    【解决方案1】:

    当您创建StopWatch 的新实例时,旧的计时器仍然处于活动状态。

    private void setGame()
    {
        if (game != null)
            game.gameData.stopWatch.StopTimer();
    
        game = new Game();
    
        game.gameData.stopWatch = new StopWatch(timerLabel);
        game.gameData.scoreLabel = scoreLabel;
    }
    

    并将StopTimer 函数添加到StopWatch 类:

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

    P.S. 这是一个快速修复,只是为了让代码正常工作。从设计的角度来看不一定正确。当使用System.Timers.Timers 时,最好实现Dispose 模式。见Is it necessary to dispose System.Timers.Timer if you use one in your application?

    【讨论】:

    • 我猜不是,StopWatch 是构造函数,而不是方法。
    • @Vitto 只是想补充一点,您可以考虑处理旧游戏和计时器。帖子已更新。
    【解决方案2】:

    确保你只打电话

    _timer.Tick += new EventHandler(_timer_Tick);
    

    一次。

    【讨论】:

    • StopWatch 不是一种方法。它是构造函数。
    猜你喜欢
    • 2016-04-04
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多