2

让我首先说,这与其说是需要解决的问题,不如说是一个问题。我现在有了解决方案,对我来说一切正常。但我想知道为什么第一次出现问题。

这是我现在拥有的代码,它像我期望的那样工作:

    private void OnNewGameStarted(Game game)
    {
        _activeGames.Add(game);

        TimeSpan delay = game.GetTimeLeft();
        var timer = new Timer(delay.TotalMilliseconds) {AutoReset = false};
        timer.Elapsed += (sender, args) => GameEndedCallback(game);
        timer.Start();
    }

    private void GameEndedCallback(Game game)
    {
        if (_statisticsManager.RegisterGame(game))
            _gamesRepository.Save(game);

        _gameStatusSubscriber.GameStatusChanged(game);
    }

我曾经使用 System.Threading.Timer 而不是 System.Timers.Timer,有时会触发计时器事件(GameEndedCallback 方法),有时不会。我找不到任何理由为什么会这样。

这是我用来初始化定时器的代码(其他部分相同):

            TimeSpan delay = game.GetTimeLeft();
            new Timer(GameEndedCallback,game,(int)delay.TotalMilliseconds,Timeout.Infinite);
        }

        private void GameEndedCallback(object state)
        {
            var game = (Game) state;

方法 OnNewGameStarted 是事件处理程序,当某些特定消息到达时,它会在 Fleck 网络服务器的方法链之后调用。

4

2 回答 2

4

有一篇关于 3 种计时器类型及其作用的帖子。主要的事情是:

  • System.Timers.Timer 用于多线程工作
  • System.Windows.Forms.Timer - 来自应用程序 UI 线程
  • System.Threading.Timer - 并不总是线程安全的!
于 2013-08-06T06:24:31.660 回答
0

Timeout.Infinite 是回调调用之间的时间间隔,以毫秒为单位。指定 Timeout.Infinite 以禁用周期性信号。请参阅 MSDN: http: //msdn.microsoft.com/en-us/library/2x96zfy7.aspx Timeout.Infinite 是用于指定无限等待期的常数。试试这个以获得对回调的定期调用

new System.Threading.Timer(GameEndedCallback, game, (int)delay.TotalMilliseconds, (int)delay.TotalMilliseconds);
于 2013-08-06T06:22:19.150 回答