我有一个表单,其焦点状态在使用以下方法的方法中进行检查:
if (!this.Focused)
{
//do something
}
但是,这也需要从另一个工作线程检查,当我(!this.Focused)
从另一个线程调用 if 时,我遇到了跨线程冲突。如何this.Focused
从另一个线程访问布尔值的真假状态?我熟悉使用委托从其他线程更新表单控件,但我对此有一个真正的问题。我错过了什么?任何帮助是极大的赞赏。
完全一样——你只需要使用 的返回值Invoke
,也就是委托的返回值:
Func<bool> func = () => this.Focused;
var focused = (bool) Invoke(func);
那这个呢?
bool focused = false;
this.Invoke((MethodInvoker)delegate
{
focused = controlname.Focused;
});
尝试,
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
focused = controlname.Focused;
});
}
else
{
focused = controlname.Focused;
}
检查更多关于 InvokeRequired http://www.codeproject.com/Articles/37642/Avoiding-InvokeRequired