System.Threading.ThreadStateException was unhandled
Message="ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment."
Imports System.Threading
Public Class Form1
Dim WaitEvent As New AutoResetEvent(False)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim thr As New Thread(AddressOf StartBrow)
thr.SetApartmentState(ApartmentState.STA)
thr.Start()
WaitEvent.WaitOne()
End Sub
Private Sub StartBrow()
Dim webBrowser As New WebBrowser
webBrowser.Navigate("Http://www.google.com")
AddHandler webBrowser.DocumentCompleted, AddressOf Web_Document_Completed
End Sub
Private Sub Web_Document_Completed(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
MessageBox.Show(e.Url.AbsolutePath)
WaitEvent.Set()
End Sub
End Class
thr.Join()
MsgBox("joined")
You are probably also preventing the DocumentCompleted event for the browser when blocking the UI thread. Add this code after you start the thread and you will see what happens:
VB.NET:thr.Join() MsgBox("joined")
I would in thread instead loop for ReadyState=Complete after the Navigate call instead of using the event, you also need Application.DoEvents() in this loop for the browser control to update. But why don't you just create the control in UI thread and handle the event there?
A general side note: add the event handler before you call the method that cause it to be raised, else you could very well miss it.
Dim web As New WebBrowser
web.Navigate("Http://www.google.com")
Do Until web.ReadyState = WebBrowserReadyState.Complete
Application.DoEvents()
Loop
MessageBox.Show(web.DocumentTitle)
No, thread.join doesn't work, like I said you add that code to get the understanding of what happened with you previous code and why it didn't work. I you didn't see it; the other thread ended and the browser instance ceased to exist before the document was loaded, then UI thread was blocking on waithandle that was never set.