Question

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;
}
Was it helpful?

Solution

The proper interval to get one second is 1000. The Interval property is the time between ticks in milliseconds:

MSDN: Timer.Interval Property

So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick event multiple times.

OTHER TIPS

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;
}

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.

Already an old thread but I just read the article from Microsoft where they mentioned that the System.Timer depends on the operating system. Which means that if you use Windows 7 and the interval is smaller than 15 milliseconds, the interval will be delayed.

You use the Interval property to determine the frequency at which the Elapsed event is fired. Because the Timer class depends on the system clock, it has the same resolution as the system clock. This means that the Elapsed event will fire at an interval defined by the resolution of the system clock if the Interval property is less than the resolution of the system clock. The following example sets the Interval property to 5 milliseconds. When run on a Windows 7 system whose system clock has a resolution of approximately 15 milliseconds, the event fires approximately every 15 milliseconds rather than every 5 milliseconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top