线程安全,Silverlight [英] Thread safe, Silverlight

查看:24
本文介绍了线程安全,Silverlight的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用 RIA WCF 服务,并且在多个 ViewModel 中注入了相同的上下文.我的问题是,如您所知,RIA 服务的上下文不是线程安全的.

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.

所以我的同步解决方案是自制的".我使用背景工作者,并使用 PostSharp,我应用我的属性[UniqueThread ("Data")] 关于方法和瞧.

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?

此致,
Vincent BOUZON

Best regards,
Vincent BOUZON

推荐答案

在我们的例子中,我们向 BaseViewModel 添加了一个 OnUiThread 方法(它还提供 INotifypropertyChanged 处理程序和一些其他方便的 util 方法).

In our case we added an OnUiThread method to our BaseViewModel (which also supplies INotifypropertyChanged handler and some other handy util methods).

每当我们需要确保在 UI 线程上完成操作时,我们都会使用 lambda 表达式(或回调)调用 OnUiThread 来完成这项工作.

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;
    });

这篇关于线程安全,Silverlight的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆