While developing Win Phone apps, there are a few options for having a timer. Here are 2 possibilities which provide precision vs. blocking/overhead:

1. Dispatch timer
This is basically a timer that runs on the UI thread and so is precise but can block the UI for any refreshes and activity when it executes, so be careful how/when you use it.

It can be declared and created as:

System.Windows.Threading.DispatcherTimer _predictionTimer = new System.Windows.Threading.DispatcherTimer();

It is set up as: (Do this in the Page loaded event, for the Page)

_predictionTimer.Interval = new TimeSpan(0, 0, TIMER_INTERVAL_SECONDS);
_predictionTimer.Tick += new EventHandler(PredictionTimerEvent);
_predictionTimer.Start();

Note: If you type in the += after the second statement, hitting Tab twice will also generate a callback stub in code (like the one below) for you.

The method to call for the timer event is written as:

void PredictionTimerEvent(object sender, EventArgs e)
{
   …do something…}

2. IDisposible timer

This timer is not very precise, but runs on its own thread and not the UI thread  and so does not block the UI. It does need to switch contexts to do anything with the UI/display. So, you need to get a handle to the UI thread to do anything with the display. I use the MVVM Light Messenger and subscribe to a message that I then send in the timer so I don’t need to do any switching myself.

It is declared as:

        IDisposable _timer;

It is created as: (Do this in the Page loaded event)

if (_timer== null)

{

        IScheduler scheduler = Scheduler.Dispatcher;

    _timer = scheduler.Schedule

                              (new Action<Action<TimeSpan>>TimerInterrupt), 
                    TimeSpan.FromSeconds(TIMER_INTERVAL_SECONDS));

}

The timer event handler is written as:

        void TimerInterrupt(Action<TimeSpan> action)         {             …do something…             action(TimeSpan.FromSeconds(TIMER_INTERVAL_SECONDS));         }

To kill the timer (while navigating away, for e.g.)

_timer.Dispose();  //kill timer

Both of the above essentially do the same thing, but there are different reasons to use either.
Hope that helps.

Advertisements