0

I had a program where on a short notice a screensaver had to be built in. The application already used a System.Windows.forms timer on a short interval basis. around 100 milis, but it runs on fast hardware and the code width that interval is short, so that part never gave latency problems.

The screen saver had to kick in after 30 minutes. For testing, i added another forms.timer setup for 6000 milis. Both in Debug mode and in Release versions these 6000 milis took about 11 secconds. I find that rather unreliable. There is no indiciation that any part of this program is slow or has a high CPU demand, and i've tested that since it had to work fast (and it all does work fast), ecept the screen saver (a black form width simple graphics) shows after roughly twice the time. Are form timers that unreliable ?

user613326
  • 2,140
  • 9
  • 34
  • 63
  • Maybe your code is using thread.sleep ? making it impossible to enter the forms timing queue – Peter Dec 19 '17 at 07:44

1 Answers1

1

System.Windows.Forms.Timer acts basically a wrapper of the native WM_TIMER message. This means that its messages are placed in the message queue of the UI thread at a time approximately close to the set Interval value. This kind of message has a lesser priority compared to other messages like user input, panting and such. This means that it's less important and that is processed depending on other messages existing in the queue and how long the latter take to be processed.

On the top of that, MSDN states that:

The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.

You should pick a more responsive timer class that isn't subject to this kind of limitations like, for example System.Timers.Timer or System.Threading.Timer. They can both be used in interface applications (especially the former, which inherits from Component) and raise their events using a thread pooling approach.

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
  • but he's reporting 11 seconds instead of 6 more must be going i think – Peter Dec 19 '17 at 07:43
  • The reason is the first one. Priority. – Tommaso Belluzzo Dec 19 '17 at 07:46
  • This would make sense if he's blocking or doing heavy work in the UI thread. If it's just sitting in the idle loop like most UI apps, though, the timer has no reason to delay. – Cory Nelson Dec 19 '17 at 16:24
  • well i think your right, what also caused the delay might be that the screen saver had some startup time (because of its graphical effects), and that might have been around 5 sec, because when i tested the screensaver with longer times it went away. But i reward you its essential that main loops should be checked. – user613326 Dec 19 '17 at 22:21