1

I want to use a timer that allows me to run a specific code at certain intervals but Winforms timer is very inaccurate. I set it to 2 seconds but it goes off as much as 48 seconds. The kind of code I am running is highly dependent on acting as soon as possible so 48 seconds is way too late to do anything.

Also I don't want the timer to eat a lot of CPU cycles because the code I am running is very simple.

Joan Venge
  • 315,713
  • 212
  • 479
  • 689
  • Uh, if it goes off *46 seconds too late*, something is suspect .. such as incorrectly blocking the UI thread. WinForms timers are dispatched on the applicable UI thread where it was created (there is normally one per "native" Window). If you want it to fire *around* a blocking thread then you'll need to introduce a different thread or use a timer that uses a different thread (that isn't being blocked). – user2246674 Jul 21 '13 at 04:16
  • Thanks, I am basically using a BackgroundWorker that calls the Monitor method. The timer is calling RunWorkerAsync. Is this bad? – Joan Venge Jul 21 '13 at 04:20
  • BGW.RunWorkerAsync *shouldn't* block. Is there any blocking code in the timer callback such as waiting on the BGW to complete? – user2246674 Jul 21 '13 at 04:21
  • I don't think so, I only parse the links using the HtmlAgilityPack, but they are only 3 pages. – Joan Venge Jul 21 '13 at 04:27
  • 2
    I have worked a lot with the timers the maximum tolerance of the timers are less than 50 milliseconds per cycle. 46 Seconds is not acceptable at all! – Mehrdad Kamelzadeh Jul 21 '13 at 04:35
  • lol yeah I can see the creation date of the links when they open so had to time it myself and when I did I saw those print outs, basically anything that were larger than 2 seconds. – Joan Venge Jul 21 '13 at 04:48

2 Answers2

2

Use the System.Timer Class. Since it's designed for multi-threaded environments it's more accurate than the timer control.

tinstaafl
  • 6,908
  • 2
  • 15
  • 22
2

Check this as well and also the MSDN comparison is really deep and complete.

By the way the most accurate timer is Stopwatch which is used for calculating the Code Execution times and other similar stuffs and it is used by Visual Studio for calculating the performance of the codes so it is clear how precise it should be. But In your case you can not make use of it. I mentioned StopWatch for your information and the other who might see this post in future.

Community
  • 1
  • 1
Mehrdad Kamelzadeh
  • 1,764
  • 2
  • 21
  • 39