Silverlight 4 Multithread
I am trying to update my Silverlight 4 interface about every one and a half seconds with new data. I connected to a WCF service using net.tcp binding and issuing callbacks from the server. To make sure that I am getting data from the service as quickly as possible, I started my proxy on my desktop inside my Silverlight application.
My question is how to get the results from the callback and update the ObservableCollection bound to the datagird? I've tried several different ways and keep getting the dreaded cross flow error.
a source to share
Use Dispatcher
BeginInvoke
. For instance: -
private void MyCallback(object sender, SomeArgsClass e)
{
// perhaps some extraction of a payload or something
Deployment.Current.Dispatcher.BeginInvoke( () =>
{
// Code you need to run on the UI thread.
});
// Note code may or may not exit here before code above has completed.
// So be careful with disposable types etc.
}
a source to share
There are several approaches:
-
use
Deployment.Current.Dispatcher
from background thread and make a call to Deployment.Current.Dispatcher.CheckAccess () on it -
pass to the dispatcher from the UI component that starts the background thread and use that handle to make the CheckAccess () call
-
this is my preferred option: pass the delegate (callback) to the background thread when it has new data that the delegate calls and that the delegate lives in the UI control - it can then use the dispatcher available to control the UI
A template for this kind of thing:
private void DoMyUIUpdate(List<object> updates)
{
if (Deployment.Current.Dispatcher.CheckAccess())
{
//do my work, update the UI
}
else
Deployment.Current.Dispatcher.BeginInvoke(new Action<List<object>>(DoMyUIUpdate), updates);
}
a source to share