问题
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" for 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 BOUZON
回答1:
In 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;
});
回答2:
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?
来源:https://stackoverflow.com/questions/3755817/thread-safe-silverlight