[c#] Timer Interval 1000 != 1 second?

I have a label which should show the seconds of my timer (or in other word I have a variable to which is added 1 every interval of the timer). The interval of my timer is set to 1000, so the label should update itself every second (and should also show the seconds). But the label is after 1 second already in the hundreds. What is a proper interval to get 1 second?

int _counter = 0;
Timer timer;

timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(TimerEventProcessor);
label1.Text = _counter.ToString();
timer.Start();

private void TimerEventProcessor(object sender, EventArgs e)
{
  label1.Text = _counter.ToString();
  _counter += 1;
}

This question is related to c# timer seconds

The answer is


Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.


Instead of Tick event, use Elapsed event.

timer.Elapsed += new EventHandler(TimerEventProcessor);

and change the signiture of TimerEventProcessor method;

private void TimerEventProcessor(object sender, ElapsedEventArgs e)
{
  label1.Text = _counter.ToString();
  _counter += 1;
}