Threading in Silverlight is simple and have very few classes and limited functionality.
In Silverlight we rarely go for the threading since the platform itself is asynchronous. Click to read how to do asynchronous programming in C# 5.0
In Silverlight the main thread is incorporated with the Dispatcher, and we can use the BeginInvoke method of the Dispatcher class to update the UI from a different thread. According to the MSDN documentation Dispatcher in Silverlight is intended for the UI updates.
I’m using a dummy method which returns a string reversed of its input. And let’s assume it takes 4 seconds to complete the task.
So we need a thread to do the work, without blocking the UI. Once the task completed we have to display the string in the UI.
Here’s my simple and the dirty UI, a TextBox, a Button and a TextBlock to show the output.
Here’s the code goes under the Button click event , you can do the work in a thread and return the updates to the UI safely using Dispatcher.
When hitting the debug and break point we can ensure that our thread is really started and running.
Code for the ReverseString method
Let’s discuss how Dispatcher can communicate across threads.
You can clearly notice that, I got the Dispatcher object using this.Dispatcher. This gives the Dispatcher of the Page (MainPage).
Dispatcher is a member of the DependencyObject class. So all the elements mainly UI controls have the Dispatcher property.
Silverlight is a Single Threaded Apartment (STA) Model. And as mentioned earlier it is incorporated with the main thread of the Silverlight. It is the thread responsible of the creation of the UI elements.
Trying to create UI elements from custom threads will throw thread exceptions as they try get the one and only Dispatcher from a different thread.
Here I compare the difference Dispatcher obrtained. First I got the Dispatcher of the RootVisual. Second the TextBlock control. Third I get the Dispatcher reference of the Deplyoment.
You can see that all Dispatchers equal. So Dispatcher works from one golden rule that is Silverlight is Single Threaded Apartment (STA) model where with that main thread Dispatcher is incorporated.