0

I have an issue with Threading.Timer in my .NET application. To make it easier to understand I made a sample.

using System; using System.Diagnostics; using System.Threading; namespace TimerTestApp { class Program { private static Timer timer; private static int timerTickCounter; private static DateTime timerStartTimer; private static readonly Stopwatch Sw = new Stopwatch(); private static readonly ManualResetEvent TimerFinish = new ManualResetEvent(false); static void Main() { Console.WriteLine("START"); timer = new Timer(TimerCallBack, null, 0, 1000); TimerFinish.WaitOne(); } private static void TimerCallBack(object state) { if (timerTickCounter == 0) { timerStartTimer = DateTime.Now; Sw.Start(); } timerTickCounter++; Console.WriteLine("timerTickCounter = {0}", timerTickCounter); if (timerTickCounter >= 1200) //20.00 min { var secondsSinceStart = (int)(DateTime.Now - timerStartTimer).TotalSeconds; timer.Dispose(); Sw.Stop(); Console.WriteLine("timerTickCounter = {0}; secondsSinceStart={1}; Stowatchseconds={2}", timerTickCounter, secondsSinceStart, Sw.Elapsed.TotalSeconds); Console.ReadLine(); TimerFinish.Set(); } } } } 

After running this code I have the very last line with resut:

timerTickCounter = 1200; secondsSinceStart=1215; Stowatchseconds=1215,7573291

As far as you can see timer ticks each second, but the resulting output says it took 15 seconds more time for program to run.

I need mechanism to update DateTime fields, and I cannot simply create a timer which ticks once a second.

Can anyone propose a solution for this?

2
  • Approach it from the other side. How much accuracy do you actually need? Do you have a calibration point? Commented Jan 5, 2013 at 17:36
  • I need an exact accuracy if it is correct to say so. No, I don't have a calibration point. Commented Jan 5, 2013 at 18:08

1 Answer 1

1

All Timers operate with a ~20ms resolution. So 15 seconds on 20 minutes is inside the expected range.

If you really need a very accurate 1/second timer than you'll need to use a one-shot timer and calculate the remainder of the second each time.

Sign up to request clarification or add additional context in comments.

3 Comments

Would you be so kind to explain it, i don't get it. You mean I need to remember DateTime.Now on each tick and calculate (Now - PrevTime)?
Yes. You need to resync, once per hour/minute/second. DateTime.Now is your only fixed reference point.
Now i got it. Thanks. Never thought that such simple operation will take so much efforts.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.