Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I developed a simple C# application .In which , I used below code.After some time (3 to 4 min),I saw that Stop watch elapsed Second does not match with timecount variable.
Can anyone help me what is wrong in below code?
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace TestApplication
{
    public partial class TimerTest : Form
    {
        Stopwatch _stopwatch = new Stopwatch();
        System.Timers.Timer TTTimer = new System.Timers.Timer(1000);
        int timecount = 0;
        public TimerTest()
        {
            InitializeComponent();

        }

        private void Startbtn_Click(object sender, EventArgs e)
        {
          
            this.TTTimer.Interval = 1000; //1 sec
            this.TTTimer.Elapsed += new System.Timers.ElapsedEventHandler(TTTimer_Elapsed);
            this.TTTimer.Start();
           // _stopwatch.Start();
        }

        void TTTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!_stopwatch.IsRunning)
                _stopwatch.Start();
            this.Invoke((Action)delegate()
            {
                label1.Text = _stopwatch.Elapsed.Hours + ":" 
                             + _stopwatch.Elapsed.Minutes + ":" 
                             + _stopwatch.Elapsed.Seconds
                             + " Count: " + timecount % 60; 
            });
            timecount = timecount + 1; //timecount++;
        }
        private void Stopbtn_Click(object sender, EventArgs e)
        {
            TTTimer.Stop();           
            _stopwatch.Stop();
            _stopwatch.Reset();

        }
    }
}
Posted
Updated 2-Oct-15 23:35pm
v3

There is no error, or not really.
The Timer does not happen as accurately as you might think - it's event driven, and had inherent delays built in due to Windows being a multitasking, message-based system. This means that while the Stopwatch value (which uses a hardware clock to read the current time each time you read it will always be right, any counting you do in the timer assumes that the tick event happens exactly every 1 second - which it doesn't. Try printing the time to the console each time the timer ticks and you will see what I mean.

What I'd suggest is that you set up an external DateTime and set it to DateTime.Now when you start the timer, then work out the time difference in the Tick handler:
C#
Timespan diff = DateTime.Now - dateTimeWeStartedAt;
Rather than relying on counting the ticks yourself.

BTW: Reading the Stopwatch value like that is going to throw up the occasional visual oddity - read the Elapsed property once into a Timespan, and then use that instead of reading it multiple times as it can change between successive reads. Significant changes can occur at the end of minutes, hours, and days!
 
Share this answer
 
Timers aren't accurate. Have a look at this article: "Timer surprises, and how to avoid them"[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900