A reader of my Silverlight 5 book recently reached out to me about threading and why I create some objects on the UI thread in the examples. We discussed some of the reasons, but I felt this would be a good topic to share with everyone. In fact, this is one area where it would have been fun to go into great detail in my book, but there simply wasn't the space. Threading and cross-thread exceptions can be a bit of a mystery to new Silverlight and WPF developers.
BackgroundThe user interface in Silverlight runs on a thread commonly known as the UI Thread. Any code you create in the code-behind, and any code it calls all the way down the chain, unless it explicitly creates another thread, runs on this same UI thread. It's not at all uncommon to see Silverlight and WPF applications which never explicitly create a second thread, but do make calls to other services which create background threads for processing. There are many other examples, but networking is one place where the Silverlight .NET Framework explicitly creates (or uses) different threads. Not all calls return on the UI thread.Threads other than the UI thread are not allowed to access or manipulate UI objects. If they attempt to do so, the runtime throws an Invalid Cross-Thread Access exception. It looks like this:
Read more: 10rem.net
QR:
BackgroundThe user interface in Silverlight runs on a thread commonly known as the UI Thread. Any code you create in the code-behind, and any code it calls all the way down the chain, unless it explicitly creates another thread, runs on this same UI thread. It's not at all uncommon to see Silverlight and WPF applications which never explicitly create a second thread, but do make calls to other services which create background threads for processing. There are many other examples, but networking is one place where the Silverlight .NET Framework explicitly creates (or uses) different threads. Not all calls return on the UI thread.Threads other than the UI thread are not allowed to access or manipulate UI objects. If they attempt to do so, the runtime throws an Invalid Cross-Thread Access exception. It looks like this:
Read more: 10rem.net
QR: