在不同的线程中运行和控制浏览器控件



我有我的主gui类和一些子类。有+-3线程正在从各种互联网来源和API网关等收集数据。

现在,在其中一个线程中,我想运行一个网络浏览器控件,这样我就可以在程序中添加一些自动浏览功能。每个子线程都应该能够自己打开网络浏览器。所以我创建了第二个c#windows表单,其中只包含web浏览控件。

我已经将此新线程上的ApartmentState.STA设置用于Web浏览器控件。但是,form2没有响应。

我尝试调用Application.Run();这使得webbrowser/form2做出响应。但随后我的主线程停止运行。

所以我有点不确定该怎么做。我想要的是可能的吗?

这应该能在中工作

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();

也就是说,我将使用WebClient或HttpWebRequest与HtmlAgilityPack一起下载和解析html资源

最新更新