C# - how do you stop a timer?

前端 未结 7 1133
面向向阳花
面向向阳花 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 09:47

    So to add to the previous answers, in case you are using the System.Threading.Timer class, this will stop it permanently with no further chance to use the same instance:

       timer.Dispose()
    

    otherwise:

      timer.Change(Timeout.Infinite, Timeout.Infinite)
    
    0 讨论(0)
  • 2020-12-08 09:48

    With each of the timers in the .NET framework, it's possible that the timer fires just before you stop it, so you'll see the callback after you stop it.

    You'll need to use something like an asynchronous callback context: use a bool set to true when you want the timer running, and set it to false when you stop it. Then have your callback check your context to see if it should really run or not.

    0 讨论(0)
  • 2020-12-08 09:57

    If you are using System.Timers.Timer you can stop like this

    timer.Enabled = false
    

    if you are using System.Threading.Timer, use this

    timer.Change(Timeout.Infinite , Timeout.Infinite)
    

    Or use

    timer.Stop(); 
    

    if you are using System.Windows.Forms.Timer

    0 讨论(0)
  • 2020-12-08 09:58

    Assuming you are making use of the System.Windows.Forms.Timer; since there was no explicit reference to anything else...if that is the case...

    System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
    myTimer.Stop(); 
    
    0 讨论(0)
  • 2020-12-08 10:05

    System.Windows.Forms.Timer: timer.Enabled = false;
    System.Threading.Timer: timer.Change(Timeout.Infinite, Timeout.Infinite);
    System.Timers.Timer: timer.Enabled = false; or timer.Stop();

    0 讨论(0)
  • 2020-12-08 10:05

    Depends on the timer. If it is from threading namespace, dispose of it and recreate it when you need to, or have your timer delegate wait on reset event(see msdn). System.Timers namespace has a start and stop method.

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