Control.Invoke错误:尚未创建句柄

时间:2012-01-31 18:51:57

标签: c# .net vb.net winforms multithreading

当某些表单中存在长时间运行的代码时(例如,在数据加载期间),我会在另一个线程上显示一个等待表单(说“请稍候...”)。我展示了这样的表格:

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调用之前,我循环直到创建句柄?谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

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