0

I have a button and a web browser control on my WinForms application. When I click on a button it fires up a browser, but until page is loaded my application hangs even though I use a separate thread for browser control.

How can I handle it so my application doesn't hang while page gets loaded?

private void button1_Click(object sender, EventArgs e)
{
    Thread mythread = new Thread(new ThreadStart(go));    
    mythread.IsBackground = true;
    mythread.Name = "mythread";
    mythread.Start();
}

void go() 
{ 
    webBrowser1.Navigate("google.com"); 
}
svick
  • 236,525
  • 50
  • 385
  • 514
motevalizadeh
  • 5,244
  • 14
  • 61
  • 108
  • 1
    Don't execute `go` in thread. – L.B Mar 10 '12 at 22:54
  • Can you please describe which web browser control did you use, maybe include a link so people quickly get an idea about it? – oleksii Mar 10 '12 at 22:58
  • web browser that include in vs 2010 tool box – motevalizadeh Mar 10 '12 at 23:08
  • 2
    You can't cheat a single-threaded component like WebBrowser. COM makes sure that the method gets executed on the thread that you created it on. – Hans Passant Mar 10 '12 at 23:21
  • you could always try this approach: http://stackoverflow.com/questions/8610197/async-await-implementation-of-webbrowser-class-for-net – jglouie Mar 11 '12 at 01:00
  • It's not quite correct to say that the WebBrowser control is "single-threaded", but it's absolutely true that you need to keep your interactions with it on the UI thread. – EricLaw Nov 01 '13 at 04:19

2 Answers2

2

I had a similar issue, the issue was resolved by using dispatcher. Using Background worker would throw you an error since you are trying in code behind.

Try the below in button click.

Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { go(); })); 

Namespace for the above is System.Threading

Darey
  • 497
  • 4
  • 24
  • In WinForms one needs to use Dispatcher.CurrentDispatcher instead. Then it works at least in the happy day scenario (didn't find a way to provoke network problem so far). – Florian Straub Jun 16 '17 at 08:31
0

After the .navigate method, do this...

Do
Sleep 100
Doevents
Loop until webbrowser1.busy = true and webbrowser1.readystate = 4

This should sort at thread out, .busy could be .isbusy on your version of wb control, look out my other web browser related answers if you want to implement a proper, more detailed method on pausing execution until web browser is truly done loading a webpage.

Ket me know how it works out for you and if I can be of any further help.

Erx_VB.NExT.Coder
  • 4,838
  • 10
  • 56
  • 92