Welcome to MSDN Blogs Sign in | Join | Help

XAML, WPF, Silverlight, .NET, Office 2007, Windows

XAML, WPF, Silverlight, .NET, Office 2007, Windows code samples and other interesting things
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 http://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.

 

Published Thursday, March 13, 2008 1:50 PM by nikola

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# More ways to turn Internet feeds into TV feeds « Jon Udell @ Tuesday, July 01, 2008 9:11 AM

PingBack from http://blog.jonudell.net/2008/07/01/more-ways-to-turn-internet-feeds-into-tv-feeds/

More ways to turn Internet feeds into TV feeds « Jon Udell

# re: Calling Web Services and Accessing UI from Timer Event in Silverlight @ Tuesday, August 26, 2008 7:56 AM

Damn... THANK you so much for this post... I saved my day.

Jakob

Leave a Comment

(required) 
required 
(required) 
Page view tracker