0

我已经基本上是同样的问题在这里讨论:http://khason.net/blog/dependency-property-getters-and-setters-in-multithreaded-environment/如何获取不在UI线程上的silverlight依赖项属性?

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

如果行标“< < < < <”会从后台线程调用的Silverlight引发InvalidOperationException和我的应用程序可能会死锁。

不幸的是,博客文章的解决方案无法工作,因为Dispatcher类的Silverlight版本隐藏了同步的Invoke方法 - 只有BeginInvoke标记为public。

回答

5

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

bool result = false; 
context.Send((c) => result = YourClass.GetMyProperty(obj), null); 

你可能要考虑重写静态方法来检查,看它是否是正确的线程,如果没有,用藏SynchronizationContext.Current值暂时切换到正确的线程检索值。

+0

工作完美,谢谢。 – 2009-07-13 19:17:29

0

您可以将BeginInvoke与在回调中触发的手动重置事件结合使用。