Hello everybody. I have a progress form in my application and some times I get the following exception.
System.InvalidOperationException:Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
Actually, I myself never got this exception. It happens seemingly randomly when in the production
environment. I cannot reproduce it. Here's the simplified code:
Private Shared MyThread As Thread = Nothing
Private Shared MyProgressForm As ProgressForm = Nothing
Public Shared Sub Start(ByVal Message As String)
' If the thread is not already running
If MyThread Is Nothing Then
MyThread = New Thread(AddressOf MyThreadSub)
MyThread.Start()
' Wait for the form to show up
While MyProgressForm Is Nothing OrElse Not MyProgressForm.IsHandleCreated
End While
MyProgressForm.Invoke(New System.Action(Of String)(AddressOf SetMessage), Message)
End If
End Sub
Private Shared Sub MyThreadSub()
MyProgressForm = New ProgressForm()
System.Windows.Forms.Application.Run(MyProgressForm)
'Whenever the form closes, go back to the initial state
MyProgressForm = Nothing
MyThread = Nothing
End Sub
Public Shared Sub [Stop]()
' If the thread is not over yet
If MyThread IsNot Nothing Then
MyProgressForm.Invoke(New Action(AddressOf MyProgressForm.Close))
' Wait for the thread to be over
While MyThread IsNot Nothing
End While
End If
End SubAnd I just call it like this:
Progress.Start("Performing operation...")
While ...
Progress.Update(...)
End While
Progress.Stop()The exception is always thrown at
MyProgressForm.Invoke(New Action(AddressOf MyProgressForm.Close))
But I don't understand why, because the Start and the Update methods were successful before. And the form cannot be unavailable while the thread is still running, because closing the form also ends the thread.
For now, I'm not looking for another way to make a progress form. My point is to understand why can't this work as it was supposed to.
Any ideas?
Thank you all.