InvokeRequired
也可能返回false,这种情况发生在你访问控件/窗体(或其父控件/窗体)的Handle
尚未创建的情况下。基本上,你的检查不完整,因此导致了你看到的结果。你需要检查IsHandleCreated
,如果它是false
,那么无论InvokeRequired
返回什么,你都需要使用Invoke
/BeginInvoke
。[更新]但是:这通常不会很稳健,因为Invoke
/BeginInvoke
会检查哪个线程创建了Handle
以实现其功能...[/更新]只有当IsHandleCreated
是true
时,你才能根据InvokeRequired
返回的结果采取行动,例如:if (control.IsHandleCreated)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
else
{
// in this case InvokeRequired might lie - you need to make sure that this never happens!
throw new Exception ( "Somehow Handle has not yet been created on the UI thread!" );
}
[更新]
因此,为避免这个问题,以下是很重要的:
在除UI线程以外的任何线程中的第一次访问之前,请始终确保Handle
已经被创建。
根据MSDN的说法,你只需要在UI线程中引用control.Handle
就可以强制它被创建-在代码中,这必须发生在任何不是UI线程的线程首次访问该控件/表单之前。
[/更新]