Calling Web Services and Accessing UI from Timer Event in Silverlight

If you try accessing UI from a timer event, you'll Exception: Invalid cross-thread access. This happens because the timer code is running on different thread and trying to access controls on the main thread. Here's how to fix it:

Edit: thanks to jackbond on the Silverlight.NET forum https://silverlight.net/forums/p/11533/36916.aspx#36916 who pointed me in the right direction.

The preferred way to do this is by using DispatcherTimer:

DispatcherTimer timer = new DispatcherTimer();

timer.Interval = new TimeSpan(1000);

timer.Tick += new EventHandler(timer_Tick);

timer.Start();

Before I was using this method, which still works but is not as good in this case (harder to read):

Action _onTimerAction = new Action(OnTimer);

Timer _timer = new Timer(new TimerCallback(delegate(object action)

                { Dispatcher.BeginInvoke(_onTimerAction); }), null, 0, 3000);

private void OnTimer()

{

    // call web service/update UI here

}

Also, I learned that Dispatcher.BeginInvoke is very usable for calling functions on the UI thread from another thread, as in the above sample.