Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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.
Comments
Anonymous
July 01, 2008
PingBack from http://blog.jonudell.net/2008/07/01/more-ways-to-turn-internet-feeds-into-tv-feeds/Anonymous
August 25, 2008
The comment has been removedAnonymous
June 04, 2009
Dalam presentasi MACO selanjutnya, saya akan membawakan materi tentang Data-Driven Services in SilverlightAnonymous
November 05, 2009
Thank you for this post - super useful :o)