Run and control browser control in different thread

蹲街弑〆低调 提交于 2019-12-17 17:16:00

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/12059752/run-and-control-browser-control-in-different-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!