如何在不在UI线程上获取silverlight依赖属性?

Ric*_*erg 0 silverlight multithreading asynchronous dependency-properties

我在这里讨论的问题基本相同:http://khason.net/blog/dependency-property-getters-and-setters-in-multithreaded-environment/

public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.RegisterAttached("MyProperty", typeof(bool),
        typeof(MyObject), new PropertyMetadata(new PropertyChangedCallback(OnMyPropertyChanged)));

public static bool GetMyProperty(DependencyObject obj)
{
    return (bool)obj.GetValue(MyPropertyProperty);     <<<<<
}

public static void SetMyProperty(DependencyObject obj, bool value)
{
    obj.SetValue(MyPropertyProperty, value);
}
Run Code Online (Sandbox Code Playgroud)

如果标记为"<<<<<"的行从后台线程调用,Silverlight会抛出InvalidOperationException,我的应用程序可能会死锁.

遗憾的是,博客文章中的解决方案无效,因为Dispatcher类的Silverlight版本隐藏了同步的Invoke方法 - 只有BeginInvoke被标记为public.

chu*_*ckj 5

在主线程中,在生成后台线程之前,将值保存在生成的线程可访问SynchronizationContext.Current的变量中context.然后尝试以下代码,

bool result = false;
context.Send((c) => result = YourClass.GetMyProperty(obj), null);
Run Code Online (Sandbox Code Playgroud)

您可能需要考虑重写静态方法以检查它是否在正确的线程中,如果不是,请使用stashed SynchronizationContext.Current值临时切换到正确的线程以检索该值.