控件.调用错误:尚未创建句柄

本文关键字:创建 句柄 调用 错误 控件 | 更新日期: 2023-09-27 18:22:06

当某些表单中存在长时间运行的代码时(例如,在数据加载期间),我在不同的线程上显示一个等待表单(说"Please wait…")。我显示这样的表格:

m_PopProcessingThread = New Thread(New ThreadStart(
     Sub()
         m_PopProcessingForm = New WaitingForm(m_Message)
         Application.Run(m_PopProcessingForm)
     End Sub))
m_PopProcessingThread.Name = "Pop Processing Thread"
m_PopProcessingThread.SetApartmentState(ApartmentState.STA)
m_PopProcessingThread.Start()

然后我就这样藏起来:

While m_PopProcessingForm Is Nothing OrElse Not m_PopProcessingForm.IsHandleCreated
    Threading.Thread.Sleep(20) 'Wait a bit for the form to be created
End While
' Dispose of the pop processing form (by disposing of this form, thread is also exited)
m_PopProcessingForm.Invoke(Sub()
                               m_PopProcessingForm.Dispose()
                           End Sub)

这个代码运行得很好,但我刚刚收到一个客户的错误报告:

Exception Type : System.InvalidOperationException
Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
   at System.Windows.Forms.Control.WaitForWaitHandle(WaitHandle waitHandle)
   at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
   at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
   at System.Windows.Forms.Control.Invoke(Delegate method)

堆栈跟踪指向我隐藏表单的代码部分。在Invoke调用之前,我循环直到创建了句柄,怎么可能没有创建句柄呢?谢谢你的帮助。

控件.调用错误:尚未创建句柄

表单可能在IsHandleCreated检查之后但在调用Dispose之前关闭。也许用户点击了表单上的[x]或按下了Ctrl-F4。