【问题标题】:Control.Invoke error: handle not yet createdControl.Invoke 错误:尚未创建句柄
【发布时间】:2012-01-31 18:51:56
【问题描述】:

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

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 调用之前,我循环直到创建所述句柄,怎么可能没有创建句柄?感谢您的帮助。

【问题讨论】:

  • 使用专门为此目的设计的 BackgroundWork 和/或 Task。
  • 我知道这有点颠倒,通常任务应该在另一个线程中,而不是等待形式。但考虑到当前代码在 99,999% 的情况下都能正常工作,我宁愿修复它也不愿更改我的所有代码。

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


【解决方案1】:

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

【讨论】:

  • 那会令人惊讶,这个表单上没有 X 按钮,并且表单不会长时间保持打开状态。
  • 我想这个错误可能是通过按 Alt-F4 发生的,但考虑到它们相互遵循,在 IsHandleCreated 和 Invoke 指令之间关闭表单会非常令人惊讶。
  • 你确实让我意识到如果用户按下 Alt-F4 可能会出现无限循环,所以谢谢你!
  • 由于 Invoke 被放置在消息队列中,您可以很容易地在检查句柄之后但在 Invoke 尝试调用之前获得 Dispose。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-12
  • 2011-10-17
相关资源
最近更新 更多