Windows Forms timer does not stop. How is this possible?

During debugging, I see that after executing the Timer.Stop() or Timer.Enabled = false Timer still works (Timer.Enabled = true). How is this possible?

+4
source share
3 answers

This is possible when you stop the timer on a workflow. For instance:

 public partial class Form1 : Form { public Form1() { InitializeComponent(); } Timer timer1; protected override void OnLoad(EventArgs e) { base.OnLoad(e); timer1 = new Timer(); timer1.Interval = 3000; timer1.Start(); var t = new System.Threading.Thread(stopTimer); t.Start(); } private void stopTimer() { timer1.Enabled = false; System.Diagnostics.Debug.WriteLine(timer1.Enabled.ToString()); } } 

Output:
True

The timer must be stopped by the user interface thread, the class automatically executes it. Just like Control.BeginInvoke (). There is a clear race, the Tick event handler can work after you stop it. This can also happen in the user interface thread if the very first timer you create is created in the workflow. For example, a screen saver. This is not great, you have to fix it.

+7
source

Calling β€œStart” after turning off the timer by calling β€œStop” will cause the timer to restart the interrupted interval. If your timer is set to a 5000 millisecond interval and you call Stop in about 3000 milliseconds, calling Start will cause the timer to wait 5000 milliseconds before raising the Tick event.

keep in mind

Calling a stop on any timer in a Windows Forms application can lead to immediate processing of messages from other timer components in the application, since all timer components work in the main thread of the application. If you have two timer components, one is set to 700 milliseconds and one is set to 500 milliseconds, and you call Stop on the first timer, your application may first receive a callback for the second component. If this proves problematic, try using the Timer class in the System.Threading namespace instead.

http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.stop.aspx

+3
source
 public void EnableTimer(bool state) { if (this.InvokeRequired) { this.Invoke(new Action<bool>(EnableTimer), state); } else { this.Timer1.Enabled = state; } } 

Try this code ...

+1
source

All Articles