Timer start time and end time calculation gives 4

2019-03-01 01:02发布

问题:

i am working on WP8 , i am using timer where i am calulating the total time.

This is how i am doing it:

timer = new DispatcherTimer();
 timer.Interval = TimeSpan.FromSeconds(1);//interval for timer is 1 sec
 timer.Tick += new EventHandler(timer_Tick);//after the timer expires, this event is fired
 timer.Start();
 startDateTime = DateTime.Now;  

 DateTime et = DateTime.Now;

   Debug.WriteLine("st is "+startDateTime+ " et is "+et);

   TimeSpan myDateResult = et - startDateTime;
   double seconds = myDateResult.TotalSeconds;
   Debug.WriteLine("difference is " + seconds);

Output which i am getting :

st is 3/25/2014 3:54:09 PM et is 3/25/2014 3:55:14 PM
difference is 64.312636

So i run completely for 1 min then its giving me 64 sec as output. why so? is this a bug ?

EDIT

Here timerCount value is 60;

private void timer_Tick(object sender, EventArgs e)
        {                                            
            timerCount--;
            if (timerCount > 0)
            {
                TimerText.Text = "Timer : "+timerCount.ToString();
            }
            else
            {
                TimerText.Text = "Timer : ";

            }            
        }

回答1:

So you are counting ticks with this timer and expecting after 60 ticks of 1s, exactly 1 minute will have passed.

It doesn't work like that. Other stuff is happening in the application, and .NET never assures it will be exactly one second between ticks.

If you want accuracy, use System.Diagnostics.Stopwatch which gives a very accurate elapsed time based on the system clock.



回答2:

You are using the wrong tool for calculating time. You should StopWatch instead of timer. Timer is used to do something that is meant to happen at a regular interval.