这是我的扩展方法:
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()为true,它创建了deletegate就好并且可以正确调用。但它一直在前进和最终失败。
关于为什么会发生这种情况的任何想法?
答案 0 :(得分:6)
你的情况是错误的 - CheckAccess()
会在 okay 修改当前线程中的对象时返回true
。
目前,您说,“如果我已经在UI线程中,请在UI线程中再次调用该方法” - 这显然会导致问题。你想说“如果我在UI线程中不,请在UI线程中再次调用该方法” - 所以你的代码应该是:
if (!control.Dispatcher.CheckAccess())