Thread safe, Silverlight

时光总嘲笑我的痴心妄想 提交于 2019-12-24 11:44:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!