Reputation: 1
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?
Upvotes: 0
Views: 344
Reputation: 273169
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.
Upvotes: 1