定时器开始时间和结束时间计算额外提供4秒

我正在使用WP8,我正在使用计时器,我正在计算总时间。

这就是我这样做的方式:

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

我得到的输出:

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

所以我完全跑了1分钟然后它给我64秒作为输出。 为什么这样? 这是一个错误吗?

编辑

 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分钟的60个滴答之后,恰好1分钟将过去。

它不像那样工作。 其他的东西正在应用程序中发生,而.NET从来没有保证它在tick之间只有一秒钟。

如果您需要精确度,请使用System.Diagnostics.Stopwatch ,它根据系统时钟给出非常精确的经过时间。

您使用错误的工具来计算时间。 你应该使用StopWatch而不是计时器。 定时器用于执行定期发生的事情。