简体   繁体   中英

Different behaviour of System.Timers.Timer and System.Threading.Timer

Let me start from saying that it's more a question than a problem that needs to be solved. I have the solution now and things work fine for me. But I wonder why problem occured first time.

This is the code I have right now and it works like I expect:

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

I used to use System.Threading.Timer instead of System.Timers.Timer and sometimes timer event (GameEndedCallback method) fired and sometimes not. I couldn't find any reason why it was that way.

This is the code I used to initilize timer (other parts are the same):

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

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

Method OnNewGameStarted is event handler and it is called after chain of methods from Fleck webserver when some certain message comes to it.

There is a post about the 3 timer types and what they do. the main things are:

  • System.Timers.Timer is for multithreading work
  • System.Windows.Forms.Timer - from the application UI thread
  • System.Threading.Timer - not always thread safe!

Timeout.Infinite is The time interval between invocations of callback, in milliseconds. Specify Timeout.Infinite to disable periodic signaling. See MSDN: http://msdn.microsoft.com/en-us/library/2x96zfy7.aspx Timeout.Infinite is a constant used to specify an infinite waiting period. Try this to get perodic calls to the callback

new System.Threading.Timer(GameEndedCallback, game, (int)delay.TotalMilliseconds, (int)delay.TotalMilliseconds);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM