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 stop a timer.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
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.
If you are using
System.Timers.Timer
you can stop like thisif you are using
System.Threading.Timer
, use thisOr use
if you are using
System.Windows.Forms.Timer
I also ran into the similar problem many times.
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.
System.Windows.Forms.Timer:
timer.Enabled = false;
System.Threading.Timer:
timer.Change(Timeout.Infinite, Timeout.Infinite);
System.Timers.Timer:
timer.Enabled = false;
ortimer.Stop();
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 totrue
when you want the timer running, and set it tofalse
when you stop it. Then have your callback check your context to see if it should really run or not.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:
otherwise: