Silverlight Timer Woes

I was just encountering a bug with using the System.Threading.Timer object in Silverlight for UnitDriven. It was very non-intuitive and sporadic so I thought I’d post some of my conclusions here just in case.

The problem was, that if I had a test that contained a BackgroundWorker that called Thread.Sleep(x) in it’s DoWork event, the timer callback would never get called. I would set the timer to fire in 5 seconds then call sleep for 30. The timer would only fire after the sleep was concluded.

I believe this is the case because Silverlight only has 1 background thread, or at least the Timer and the BackgroundWorker are sharing the same thread. So even though the timers timeout has expired it cannot get CPU time to do the work and fire the callback. The solution I came up with was to, instead of using a timer, simply call Application.Current.RootVisual.BeginInvoke(this.CheckForTimeout) and do the calculation myself. That worked like a charm.

So my conclusion is that getting yourself onto the UI thread in Silverlight is a more reliable way of guaranteeing CPU time since the UI thread is more likely to pumping continuously. Of course too much of that and everything will seem sluggish. What I really need is a backround work queue, or a dispatcher for a background thread in other words.

Drop a brain bomb

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s