ern*_*est 1 c# wpf extension-methods
这是我的扩展方法:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我如何称呼它:
tbManufacturer.SetThreadSafeProperty(() => tbManufacturer.Text, "test");
Run Code Online (Sandbox Code Playgroud)
在调试之后,看起来它陷入了无限循环.CheckAcess()为true,它创建了deletegate就好并且可以正确调用.但它继续前进并最终失败.
有关为什么会发生这种情况的任何想法?
你的条件是错误的 - 在可以修改当前线程中的对象时CheckAccess()返回.true
目前,您说,"如果我已经在UI线程中,请在UI线程中再次调用该方法" - 这显然会导致问题.你想说"如果我不在 UI线程中,请在UI线程中再次调用该方法" - 所以你的代码应该是:
if (!control.Dispatcher.CheckAccess())
Run Code Online (Sandbox Code Playgroud)