Meta-Knight
Meta-Knight

Reputation: 17845

Control.Invoke error: handle not yet created

I show a waiting form (saying "Please wait...") on a different thread when there is long-running code in some forms (for example, during data loading). I show the form like this:

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()

Then I hide it like this:

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)

This code works great, but I just got a bug report from a customer:

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)

The stack trace points to the part of code where I hide the form. How could the handle not have been created, when just before the Invoke call, I loop until said handle is created? Thanks for your help.

Upvotes: 0

Views: 999

Answers (1)

The form was probably closed after your IsHandleCreated check but before Dispose was invoked. Perhaps the user clicked the [x] or presssed Ctrl-F4 on the form.

Upvotes: 2

Related Questions