Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Thread.Sleep(x) interfere with Timer/Stopwatch?

Tags:

vb.net

I'm wondering if there are any unseen consequences of using Thread.Sleep(x) in my program while running Timers or a StopWatch...

I have a stopwatch that is running to count the time between user button presses and a Timer that ticks at 1s intervals to update a clock.

Will using Thread.Sleep(x) while either of these are running cause problems with accurate timing? (Most importantly the stopwatch)

like image 426
William Morschauser Avatar asked Feb 28 '26 07:02

William Morschauser


1 Answers

Nothing can directly interfere with a Stopwatch; the object is passive, only updating when started or stopped, and reporting and reacting based on the return values of the low-level QueryPerformanceCounter and QueryPerformanceFrequency API. Power-management events such as suspend, hibernation, or dynamic CPU clock speed variation are the few things that can cause problems with this.

As for the Timer classes... which one, and does it need to manipulate UI objects when it fires? If so, don't just Sleep on the UI thread, no matter which timer you choose.

System.Windows.Forms.Timer is bound to the thread it was created on, and if that thread blocks without pumping messages (which Sleep will do) its Tick event will be delayed until that thread can pump events again.

System.Threading.Timer will queue its tick to the thread pool, so barring massive interference it is unlikely to be disrupted. However, due to use of the thread pool, the tick handler cannot directly manipulate UI objects; it will need to marshal the call to the UI thread with Invoke, and Invoke will block if the UI thread is sleeping or otherwise not pumping messages.

System.Timers.Timer is probably the most complicated of the lot; it can be configured with a synchronization provider to marshal the calls to the correct synchronization context, but it too can do nothing to update the UI if the UI thread is sleeping or otherwise not pumping messages.

like image 137
Jeffrey Hantin Avatar answered Mar 02 '26 05:03

Jeffrey Hantin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!