Retrieving Elapsed Time Using the DispatchTimer Parameter Accurate to 1 Millisecond

I'm trying to measure the elapsed time in milliseconds between keypress events using a send timer, but when declaring a send timer with an interval of 1 millisecond and then setting a tick event does not work every 1 millisecond, but somewhere like 10-100 milliseconds (guess). How can I accurately measure time in milliseconds if this event does not fire on time? I am doing this in silverlight, which does not seem to have access to System.Timers. The same thing happens with System.Threading.Timer.

Here's the basics of the code:

public void StartTimer(object o, RoutedEventArgs sender) { System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer(); myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1); // 1 Milliseconds myDispatcherTimer.Tick += new EventHandler(Each_Tick); myDispatcherTimer.Start(); } // A variable to count with. int i = 0; public void Each_Tick(object o, EventArgs sender) { i++; } public void keypress(object s, EventArgs args) { label1.contents = i.ToString(); i = 0; } 

Any ideas?

+4
source share
2 answers

Silverlight's System.Threading timer only works with an accuracy of 20 ms. Usually you need a multimedia timer if you need a better resolution, but you cannot access them directly in Silverlight. At the same time, with some significant tweaks and compromises, I read that you can get a Silverlight timer with an accuracy of ~ 3 ms. See Documents referenced here:

http://blogs.msdn.com/b/nikola/archive/2009/08/19/exposed-5-methods-to-create-game-loop-which-is-the-best.aspx

Please note that I have not tested all of these alternatives myself, but they deserve attention.

Another alternative is the recently introduced System.Diagnostics.Stopwatch class. Unfortunately, this is only occasionally a high-resolution timer, depending on the equipment used. And MS documents do not indicate how they determine whether this is really high resolution or not, so your only option is to check the IsHighResolution property.

+2
source

Start aa Stopwatch and simply subtract the current stopwatch that has passed milliseconds from the last milliseconds that you need to save in a variable each time you press a key.

  private Stopwatch _stopwatch; private int _lastElapsedMs; public void StartTimer(object o, RoutedEventArgs sender) { _lastElapsedMs = 0; _stopwatch = Stopwatch.StartNew(); } public void keypress(object s, EventArgs args) { int elapsedMs = (int)_stopwatch.ElapsedMilliseconds; int currentElapsed = (elapsedMs - _lastElapsedMs); _lastElapsedMs = elapsedMs; label1.contents = currentElapsed.ToString(); } 
+4
source

All Articles