High-precision timers in managed code

CE supports a Multimedia timer, though it’s not in CF 1.0 or 2.0.  We’ve rectified that in SDF 2.0 (though your platform must support the Multimedia timer to use it – meaning WM and PPC are out).

So what do high-performance timers buy you?  Well if you look at how a regular timer works, they run at a really low priority and are horrible if you want anything that resembles deterministic behavior.  If you set the interval to say 1000ms, it’s guaranteed to not fire in less than 1000ms, but there’s actually no upper bound at all.  Jitter of 50ms (5%) would not be exceptional and in fact I’ve seen substantially worse on systems with a high load.

Our Timer2 class (name is still not finalized, so don’t finalize on it) is based on the desktop’s Timer class and provides things like a one-shot capability (timer fires once and never again without you having to disable it) and if you derive from it you can have it run a callback instead of raising an event.

Here’s a quick example of usage:

void StartMyOneshotTimer
  // create a timer
  Timer2 oneShot = new Timer2();

  // make it a one-shot timer
  oneShot.AutoReset = false;

  // fire 3 seconds from enabling
  oneShot.Interval = 3000;

  // allow 10ms latitude for when it fires
  // so it will fire between now + 2995 and now + 3005
  oneShot.Resolution = 10;

  oneShot.Elapsed += new ElapsedEventHandler(oneShot_Elapsed);


void oneShot_Elapsed(object sender, ElapsedEventArgs e)
  // do something here

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s