2014-11-20 28 views
1

这里是我的扩展方法:的WPF控件的extenstion方法引起StackOverflowException

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

而这里的如何,我叫它:

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

调试它之后,它看起来像它陷入无限循环。 CheckAcess()是真的,它创建的deletegate只是罚款和调用正确。但它不断前进并最终失败。

关于这可能发生的原因的任何想法?

+0

与调试器断点运行它,看看问题变得明显。 – 2014-11-20 19:36:52

+3

它应该是相反的:'if(!control.Dispatcher.CheckAccess())' – Clemens 2014-11-20 19:37:24

+0

@Clemens就是这样,谢谢! – ernest 2014-11-20 19:42:07

回答

6

你的条件错了 - CheckAccess()将返回true当它是好吧修改当前线程中的对象。

当前,您说“如果我已经在UI线程中,请在UI线程中再次调用该方法” - 这显然会导致问题。你想说“如果我不 UI线程,在UI线程再次调用方法” - 让你的代码应该是:

if (!control.Dispatcher.CheckAccess()) 
+1

啊,是的。我将WinForm库转换为WPF和InvokeRequired属性具有相反的效果。有用。谢谢! – ernest 2014-11-20 19:41:07