Digits
Digits

Reputation: 1351

Run and control browser control in different thread

I have my main gui class with some subclassess. There are +- 3 threads that are collecting data from various internet sources and API gateways etc.

Now, out of one of these threads, I want to run a webbrowser control, so I can add some autobrowsing functionality to my program. Each of the sub threads should be capable of opening a webbrowser on its own. So I created a second c# windows form, which contains only the webbrowsing control.

I already use the ApartmentState.STA setting on this new thread for the webbrowser control. However, the form2 is unresponsive.

I tried to call Application.Run(); from this thread, and this makes the webbrowser/form2 responsive. But then my main thread stops running.

So I'm a bit unsure on how to proceed. Is what I want possible at all ?

Upvotes: 1

Views: 6995

Answers (1)

L.B
L.B

Reputation: 116108

This should work

var th = new Thread(() =>
{
    WebBrowserDocumentCompletedEventHandler completed = null;

    using (WebBrowser wb = new WebBrowser())
    {
        completed = (sndr, e) =>
        {
            //Do Some work

            wb.DocumentCompleted -= completed;
            Application.ExitThread();
        };

        wb.DocumentCompleted += completed;
        wb.Navigate(url);
        Application.Run();
    }
});

th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();

that said, I would use WebClient or HttpWebRequest together with HtmlAgilityPack to download and parse html resources

Upvotes: 7

Related Questions