An extenstion method for a WPF control is causing an StackOverflowException

Here's my extension method:

public static void SetThreadSafeProperty<T>(this System.Windows.FrameworkElement control, Expression<Func<T>> property, T value)
{
    if (control.Dispatcher.CheckAccess())
    {
        var del = new SetThreadSafePropertyDelegate<T>(SetThreadSafeProperty);
        control.Dispatcher.Invoke(del, control, property, value);
    }
    else
    {
        PropertyInfo propertyInfo = GetPropertyInfo(property);
        if (propertyInfo != null)
        {
            propertyInfo.SetValue(control, value, null);
        }
    }
}

And here's how I'm calling it:

tbManufacturer.SetThreadSafeProperty(() => tbManufacturer.Text, "test");

After debugging it, it looks like it gets stuck in an infinite loop. CheckAcess() is true and it creates the deletegate just fine and invokes correctly. But it keeps going and going and eventually fails.

Any ideas on why this might be happening?

Jon Skeet
people
quotationmark

You've got your condition the wrong way round - CheckAccess() will return true when it's okay to modify the object in the current thread.

Currently, you're saying, "If I'm already in the UI thread, call the method again in the UI thread" - which obviously causes problems. You want to say "If I'm not in the UI thread, call the method again in the UI thread" - so your code should be:

if (!control.Dispatcher.CheckAccess()) 

people

See more on this question at Stackoverflow