This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on

Monday, June 29, 2009

TimeSpan ‘Ticks’

Using a bit of a misleading nomenclature, one of the constructors for TimeSpan uses ‘Ticks’ to initialize the object.

I have been using Environment.TickCount for eons, it seems, where 1000 ‘ticks’ equals one second.  Because of some of the processing I’m doing right now, I decided to use DispatchTimer to simplify pushing info back to the UI thread from background data refreshes.

Here’s some code that looks innocent enough:

_dispatchTimer.Interval = new TimeSpan(3000);
_dispatchTimer.Tick += new EventHandler(dispatcherTimer_Tick);
_dispatchTimer.IsEnabled = true;

Unfortunately, when run, the timer is firing (or at least trying to) approximately every 1ms.  Which…is about as fast as it’ll go.  In fact, I was getting 12-16 lines of output in my logger from the tick event firing about every 11ms. Oops.

Now, had I read the tooltip from the constructor or otherwise checked the doc’s, I would have seen that TimeSpan actually accepts ticks as 100 nanoseconds.

So, in passing in 3000 as the parameter for the constructor I was actually telling it to tick every 0.000003 seconds. Nice.

Ahem. That should read:

_dispatchTimer.Interval = new TimeSpan(30000000);

…if you don’t want your UI wiggin’ out.

No comments:

Post a Comment