JoeR JoeR - 4 days ago 7
C# Question

Waiting for WebBrowser ajax content

I want to pause the execution of my thread until a particular div has been loaded via ajax into a WebBrowser instance. Obviously I can continuously check for the presence of this div doing something like:

while (Browser.Document.GetElementById("divid") == null) { Thread.Sleep(200); }


However, sleeping the thread that the Browser is in between loops only blocks the browser from actually loading the content in the first place. It seems, therefore, that I need to execute the
Browser.Navigate
method in a separate thread - I can then continue to check/wait for the presence of the div whilst the WebBrowser instance continues loading the URL I asked it to.

My attempts at this, however, have failed and I'd value any input on how I should go about this. I thought simply dispatching a new thread with
new Thread(() => { Browser.Navigate(url); });
would work but after doing so, nothing loads and the Browser.ReadyState remains as 'Uninitialized'. I presume I'm misunderstanding how to go about properly threading procedures like this with C# and would value some advice!

Answer

Don't block the main thread's message pump. Since the browser is an STA component, xmlhttprequest won't be able to raise events from the background thread if you block the message pump. You can't navigate in a background thread. The Windows Forms wrapper of the webbrowser ActiveX does not support access from other threads than the UI thread. Use a timer instead.

Comments