【发布时间】: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