BackgroundWorker的和WebBrowser控件 [英] BackgroundWorker and WebBrowser Control

查看:252
本文介绍了BackgroundWorker的和WebBrowser控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能/推荐使用后台工作线程与Web浏览器控件?

Is it possible/recommended to use background worker threads with the web browser control?

我创建一个机器人,搜索谷歌的关键字,然后检查在网站第10页,看是否有网站排名。

I am creating a bot that searches google for keywords, then checks for sites in the first 10 pages to see if a site is ranked.

用户最多20个站点的检查可以提供,并可以使用代理。所以最好我想有5个线程同时工作。

The user can provide a maximum of 20 sites to check, and can use proxies. So ideally I'd like to have 5 threads working at once.

这可能吗?我可能听说过的地方,有与WebBrowser控件和线程的问题。

Is it possible? I might have heard somewhere that there are problems with WebBrowser control and threads.

推荐答案

这是不。 web浏览器使用Internet Explorer这是一个COM组件。 COM组件有一个线程模型,IE使用公寓。这是一个昂贵的话,这意味着它不是线程安全的。你被允许调用它的方法在BGW,但COM会自动封送调用UI线程。由于所有的方法调用和属性访问实际上是在UI线程上发生,你将使它的的使用BGW。

It is not. WebBrowser uses Internet Explorer which is a COM component. COM components have a threading model, IE uses "Apartment". Which is an expensive word that means it is not thread-safe. You are allowed to call its methods in a BGW but COM will automatically marshal the call to the UI thread. Since all method calls and property accesses actually happen on the UI thread, you will make it slower by using a BGW.

您可以在事实上在另一个线程上运行web浏览器,你就必须在该线程创建它的一个实例。你将不得不创建一个线程,就是所谓的单线程公寓。 STA,你可能会从一个WinForms或WPF应用程序的main()方法[STAThread]属性识别的缩写。更改工作线程STA需要调用Thread.SetApartmentState()开始之前。你不能为BGW做到这一点。而线程必须泵消息循环来实现STA的合同,它必须调用Application.Run()。按要求,为一体,让web浏览器,以提高其事件。 这个答案显示方式。

You can in fact run WebBrowser on another thread, you'll have to create an instance of it on that thread. And you will have to create a thread that is a so-called Single Threaded Apartment. STA, an acronym you might well recognize from the [STAThread] attribute on the Main() method of a Winforms or WPF application. Changing a worker thread to STA requires calling Thread.SetApartmentState() before you start it. You cannot do this for a BGW. And the thread must pump a message loop to implement the STA contract, it must call Application.Run(). Required, for one, to get WebBrowser to raise its events. This answer shows the approach.

考虑使用WebRequest类

Consider using the WebRequest class.

这篇关于BackgroundWorker的和WebBrowser控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆