Silverlight 2 threading issues, Quickstarts not working

I’ve been working on a Silverlight tutorial involving reading an RSS feed. Silverlight has a SyndicationFeed class which is meant to make this easy – as Microsoft’s Scott Barnes enthuses here.

It is handy, but I discovered that the Quickstart Barnes refers to does not work in Silverlight 2 Beta 2. The Quickstart section on Silverlight.net needs some work. Even if you get to this Quickstart via the link for Silverlight 2 Beta 2 examples on this page, it is soon apparent that it is actually for Silverlight 2 Beta 1. Click the Run It button and you’ll see that it asks for the older runtime.

The code doesn’t work in Beta 2 either; and as so often with thread-y stuff, it’s not immediately clear what’s going wrong. I got a blank page and the following message in the Debug output window in Visual Studio:

A first chance exception of type ‘System.UnauthorizedAccessException’ occurred in mscorlib.dll

In situations like this I recommend breaking on all CLR exceptions (Debug – Exceptions – check the Thrown box for Common Language Runtime exceptions in Visual Studio). Run again; and this time Visual Studio stops on the line which updates a Silverlight TextBlock:

feedcontent.Text += "* " + item.Title.Text + Environment.NewLine

with the message “Invalid cross-thread access”:

Rooting about a bit, I found this post from Karen Corby on changes in Silverlight 2 Beta 2:

HttpWebRequest’s delegates are called on a new non-UI thread.

  • Delegates were previously always called on the UI thread.
  • You must invoke back on to the UI thread if the data you’re retrieving will be consumed by a UI element.
  • For an example, see the updated networking post series (part one).

What this means is that you have two doses of asynchronous coding to think about if you use HttpWebRequest. First, the request itself; and second, in the code you write for the response handler if it needs to update the UI – which in most cases it will.

The example referenced by Corby shows a neat solution using a SynchronizationContext object, or you can use the Dispatcher class as explained by Wilco Bauwer here – he also draws attention to locking issues. See also Shawn Wildermuth’s post though note that CheckAccess is available despite what is said here.

This adds a significant dose of complexity to Silverlight coding. I’m not sure if any of this will change again in the final release.

I also noticed that VB coders are not well served by the Silverlight examples out there, which are overwhelmingly C#. Looks like this is the language of choice if you want an easy life.