且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

BackgroundWorker的和WebBrowser控件

更新时间:2023-12-06 13:51:40

这是不。 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.