C# - how do you stop a timer?

前端 未结 7 1134
面向向阳花
面向向阳花 2020-12-08 09:44

I know it sounds stupid, but I\'ve tried everything to stop a timer, but the timer won\'t stop. I\'m working on a game and i would appreciate if someone could tell me how to

相关标签:
7条回答
  • 2020-12-08 10:12

    I also ran into the similar problem many times.

    //Timer init.
     var _timer = new System.Timers.Timer
    {
        AutoReset = true, 
        Enabled = true,
        Interval = TimeSpan.FromSeconds(15).TotalMilliseconds //15 seconds interval
    };
     _timer.Elapsed += DoSomethingOnTimerElapsed;
    
    
    //To be called on timer elapsed.
    private void DoSomethingOnTimerElapsed(object source, ElapsedEventArgs e)
    {
        //Disable timer.
        _timer.Enabled = false; //or _timer.Stop()
        try
        {
            //does long running process
        }
        catch (Exception ex)
        {
    
        }
        finally
        {
            if (_shouldEnableTimer) //set its default value to true.
                _timer.Enabled = true; //or _timer.Start()
        }
    }
    
    
    //somewhere in the code if you want to stop timer:
    _timer.Enabled = _shouldEnableTimer = false;
    
    //At any point, if you want to resume timer add this:
    _timer.Enabled = _shouldEnableTimer = true;
    

    Why to do so?

    Lets assume, the code inside the try block takes more time. So, by the time you disable timer (_timer.Enabled = false or _timer.Stop()), there is high possibilty that the code inside try block is still executing. Hence, after completion of the task when it comes to finally, it is again enabled if there is no flag(_shouldEnableTimer) check. Therefore, I prevent your problem by adding an additional flag check.

    For more clarity, please go through the code and the added comments. Hope this helps.

    0 讨论(0)
提交回复
热议问题