I have a method browseWebsite() which browses a website using a webbrowser control to change data within that website automatically. The webbrowser control gets instantiated when the method gets executed. Unfortunately parts of the website that gets opened is loaded through ajax so the webbrowser control cannot detect the correct time of loading completion of the website, which means I cannot use the DocumentCompleted event to move further when the page is loaded. To work around that I instantiate a System.Windows.Forms.Timer to wait for 10 seconds until he makes the browser to do the move further on the website. (Thread sleep does not work since the webbrowser freezes together with the thread and stops the loading process)
The whole thing looks like this:
private void Form1_Load(object sender, EventArgs e)
{
Thread thread = new Thread(() => browseWebsite());
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
public void browseWebsite()
{
WebBrowser browser = new WebBrowser();
browser.Navigate("somesite");
Timer waitTimer = new Timer();
waitTimer.Interval = 10000;
waitTimer.Tick += delegate (object sender, EventArgs e) { WaitTimer_Tick(sender, e, browser); };
waitTimer.Start();
}
private void WaitTimer_Tick(object sender, EventArgs e, WebBrowser browser)
{
browser.Navigate("somewhere else");
}
Since the complete process this method does is pretty long and complex and I don't want to mess up my main thread having 50 of those webrowsers clicking around within it, I'd like to start that procedure within another Thread. Unfortunately the thread dies when the last line of the method is reached and takes the webbrowser and the timer with it. Is there a way to instantiate a procedure like that? Or keep the thread alive?