views:

219

answers:

2

I have essentially the same problem discussed here: 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);
}

If the line marked "<<<<<" gets called from a background thread, Silverlight throws an InvalidOperationException and my app will probably deadlock.

Unfortunately the solution from the blog post won't work because the Silverlight version of the Dispatcher class hides the synchronized Invoke methods -- only BeginInvoke is marked public.

A: 

You could use BeginInvoke in conjunction with a manual reset event that triggers on the callback.

Spencer Ruport
+4  A: 

In the main thread, before spawning the background thread, save the value of SynchronizationContext.Current in a variable called context accessible to the spawned thread. Then try the following code,

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

You might want to consider rewriting the static method to check to see if it is in the right thread, and if not, use a stashed SynchronizationContext.Current value to switch to the correct thread temporarily to retrieve the value.

chuckj
Worked perfectly, thanks.
Richard Berg