开发者

Timer is starting late, hence shows the time which is a second late then actual time

I have a timer. But it starts a second late.I mean, i am clocking a time according to the timer. But the time in the clock, which updates through timer, is one second less then the actual time elapsed. The timer starts off a second late. How to set my timer to start at right time to show actual time? this is the code inside tick event:

 if (currentState == play)
 {
     m_StatusLabel.Text = String.Format("Playing {0} ", format(tim开发者_运维知识库eCounter));
     timeCounter++;
 }

Here timeCounter is updating with each second.


Standard System.Windows.Forms timers give no guarantees about 'metronome quality'. For that, you would need either a Systems.Threading.Timer or a System.Timer.

Ref: Comparing the Timer Classes in the .NET Framework Class Library


There are no timers available that will gaurantee true-time accuracy, not even System.Threading.Timer can do that. For example, when you ask Threading.Timer to fire in 30ms, it might actually take 40ms or 200ms. Or if you ask for 1 second, it might fire in 1.01 seconds. In won't take long before your time is inaccurate.

The reason for this is that the timer makes the callback thread schedulable, but it still takes time for the thread scheduler to actually call the thread. Various operations the system is performing can delay that callback.


A Windows timer makes only one guarantee: it won't fire before the timeout interval elapses. Specifically, a thread will never receive a timer event while there are messages in its message queue.

Consequently you can't use timers to implement a clock. If you want to update a status message to show how long something has been playing, then you could try this: record the start time, and when your timer ticks get the current time, subtract the start time, and dislay the difference. Your status message won't be updated exactly every second, but when it is updated it will be correct.


Show a number 1 greater:

if (currentState == play)
     m_StatusLabel.Text = String.Format("Playing {0} ",
                                        format(++timeCounter) );

NOTE

Please consider the reason of those who suggested displaying the elapsed time as current time - start time. That is the way this is usually done. It is more accurate; a timer can be irregular on a busy system. It is still possible to update the displayed value every second. Pseudo code here for now(). This requires acquiring current time and performing a time difference.

if (currentState == play)
     m_StatusLabel.Text = String.Format("Playing {0} ",
                                  format( (now() - start)/1000 );

See Also:
1. DateTime.Subtraction
2. DateTime.Now

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜