0

I have a WebBrowser control that I'm telling to navigate to a couple webpages. My code below works fine, for one navigation. When code piece 2 gets executed, I get the COM object that has been separated from its underlying RCW cannot be used. error. I'm assuming it's because my web browser is being disposed or something with the threads, but it's a global variable! I should be able to reuse it! So I just want to access a couple of webpages and retain state, and I need to use the WebBrowser class.

//browser is a global 
browser = new WebBrowser();
browser.DocumentCompleted += browser_DocumentCompleted;

// code piece 1
Thread t = new Thread(() =>
{
   browser.Navigate(MAIN_URI);
   Application.Run();
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();

// code piece 2
Thread t = new Thread(() =>
{
   browser.Navigate(DIFFERENT_URI);
   Application.Run();
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();

// code piece 3
private static void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedArgs args)
{
   // getting document data and stuff  
   Application.Exit();
}
user3112658
  • 121
  • 2
  • 8
  • Why do you spawn these threads in the first place, when you `Join` them immediately without any other activity on the spawning thread? – spender Jun 03 '14 at 22:18
  • @spender These are just the relevant code pieces. There is a lot more going on. – user3112658 Jun 03 '14 at 22:37
  • I'm surprised it works even for a single navigation. `WebBrowser` object is a wrapper around WebBrowser ActiveX Control which requires to be created, accessed and destroyed on the *same* STA thread. Perhaps, you can borrow some code from here: http://stackoverflow.com/a/22262976/1768303 – noseratio Jun 04 '14 at 00:29
  • @Noseratio Well I have [STA Thread] above the method calling the code containing the above pieces of code. That's weird that it all needs to be in the same thread, because the documentCompleted event doesn't even trigger if I don't navigate in a new thread like i'm doing above... That's why I have start and then join, because I don't care about parallelism. Also the link looks semi-useful, but I need to use the same browser object for my navigations to save state... – user3112658 Jun 04 '14 at 18:23

0 Answers0