I have a global WebBrowser
object which is initialized in my constructer. After I use that object in a thread - in order to turn my code into a synchronous state - I am not able to use it afterwards thread ends. Here is the error I receive:
COM object that has been separated from its underlying RCW cannot be used.
I generated an Windows Form class to re-produce the error;
public partial class Test : Form
{
private WebBrowser _wb;
public Test()
{
InitializeComponent();
_wb = new WebBrowser();
}
private void NavigateThroughTread(string url)
{
var th = new Thread(() =>
{
_wb.DocumentCompleted += PageLoaded;
_wb.Navigate(url);
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
while (th.IsAlive) { }
}
private void PageLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//Page Loaded
Application.ExitThread(); // Stops the thread
}
private void button_Click(object sender, System.EventArgs e)
{
NavigateThroughTread("http://www.example.com/");
// Here the thread is finished
MessageBox.Show(_wb.DocumentText); // error <COM object that has been separated from its underlying RCW cannot be used.>
}
}
So my question is, how can I use the object _wb
after I use it in a thread.