Dispatch my stuff to the right thread
Silverlight 2 does support threads through much of the same API as the big .NET FX. So you use classes in System.Threading such as Thread and ThreadPool. Or you can use the higher-level BackgroundWorker type from System.ComponentModel. This is anyway the recommended approach.
private
void btnWorker_Click(object sender, RoutedEventArgs e)
{
_bkgndWorker = new BackgroundWorker();
_bkgndWorker.DoWork += new DoWorkEventHandler(_bkgndWorker_DoWork);
_bkgndWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bkgndWorker_RunWorkerCompleted);
_bkgndWorker.ProgressChanged += new ProgressChangedEventHandler(_bkgndWorker_ProgressChanged);
_bkgndWorker.WorkerReportsProgress = true;
_bkgndWorker.WorkerSupportsCancellation = true;
_bkgndWorker.RunWorkerAsync(10000);
}
From the various event handlers, you can freely access any UI elements because the class magic makes your code run within the UI thread. In .NET FX, when you use plain threads, or the thread pool, you can't directly access UI elements because of thread is different from the UI thread and the UI elements are not thread-safe.
Silverlight 2.0 offers a facility to cross the thread boundaries and reach directly the UI thread. It's not magic or a different runtime. It's simply a facility to make your coding easier. Here's how it works.
private
void btnThread_Click(object sender, RoutedEventArgs e)
{
ThreadStart code = new ThreadStart(DoSomething);
Thread t = new Thread(code);
t.Start();
}
private
void DoSomething()
{
Thread.Sleep(5000);
this.Dispatcher.BeginInvoke( delegate {
lblThreadOutput.Text = "Updated from a background, non-UI thread.";
});
}
The Dispatcher property on the UserControl class does the trick. It refers to a System.Windows.Threading.Dispatcher object that offers a BeginInvoke method through which you specify the code that it has to dispatch to the right UI thread. You pass BeginInvoke either an anonymous delegate or a function pointer. Nice and effective. One of those things that Silverlight does better than the big .NET FX.