Thread safe, Silverlight
I use very often RIA WCF Services and I inject the same context in several ViewModel. My problem is that as you know, the context of RIA Services, is not thread safe.
So I my solution "home made" 开发者_如何学Gofor synchronization. I use backgrounds workers, and using PostSharp, I apply my attribute [UniqueThread ("Data")] on the method and voila.
Do I complicate things? Are there simpler solutions?
Best regards,
Vincent BOUZONIn our case we added an OnUiThread method to our BaseViewModel (which also supplies INotifypropertyChanged handler and some other handy util methods).
Whenever we need to ensure an operation is done on the UI thread we call OnUiThread with a lambda expression (or a callback) to do the work.
protected delegate void OnUiThreadDelegate();
protected void OnUiThread(OnUiThreadDelegate onUiThreadDelegate)
{
if (Deployment.Current.Dispatcher.CheckAccess())
{
onUiThreadDelegate();
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(onUiThreadDelegate);
}
}
An example of a call might look like:
this.OnUiThread(() =>
{
this.ViewModelList = resultList;
});
That certainly seems excessively complicated, unless you've already done a lot of other work to force your viewmodels to be running on separate threads. By default, of course, anything you write is going to be running on the main foreground thread, and there shouldn't be any need to engage in the sort of complicated stuff you're describing. Or are your view models actually running on separate (background) threads?
精彩评论