windows phone DispatcherTimer precision

2019-09-11 03:46发布

问题:

So, i got an application (windows phone 7.5 over c#) using an DispatcherTimer to emulate a timer. I have set the interval to 1 millisecond:

timer.Interval = new TimeSpan(0,0,0,0,1);

Then i am declaring a TimeSpan in order to make a simple countdown:

TimeSpan countdown = TimeSpan.FromSeconds(10);

On each tick im Substracting 1 millisencond:

countdown = countdown.Subtract(TimeSpan.FromMilliseconds(1));

In Visual Studio's windows phone emulator 256/512 its working with 'no problems', but when i run it on my phone (LG Quantum) it seems to have precision problems. I have compared it with my PC screen running the application and its way slower on the phone. I have tried to not to run the application in debug mode in my phone. Is there any solution to this? Or i have to take another approach?

回答1:

Experience tells me that you're simply trying to fire far too many events for the phone hardware to handle.

From MSDN:

The DispatcherTimer is reevaluated at the top of every DispatcherTimer loop.

Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs.

Remember that the actual phone hardware is single core so trying to capture precisely 1000 events per second isn't the best approach.

Either increase the time between ticks and increment based on the new interval, or take the time the timer is started and subtract it from the current time each tick.



回答2:

A different approach would be better here:

  1. Record the current time when you start the timer

    DateTime startTime = DateTime.Now;
    
  2. Each time your timer ticks, recalculate the countdown

    TimeSpan countdown = DateTime.Now - startTime;