Web浏览器控制在不同的线程中 [英] Webbrowser controls in separate threads
问题描述
我正在开发一个项目,在这个项目中,在不同的类中创建了几个WebBrowsers,在这些项目中,一个新的线程开始做一些导航使用webbrowser并通过设置传递给类的ListViewItem的子项来报告事物。
我需要多次创建一个新的WebBrowser,并且每个都运行一个UI的不同线程,以避免冻结UI。如果我没有将线程的ApartmentMode设置为STA,我会收到错误:
Hi,
I'm working on a project where several WebBrowsers are created in separate classes, and in those, a new thread is started to do some navigation with the webbrowser and reports things back by setting the subitems of a ListViewItem passed to the class.
I need to create a new WebBrowser several times and have each running on a different thread to the UI to avoid freezing the UI. If I don't set the thread's ApartmentMode to STA, I get the error:
System.Threading.ThreadStateException: 'ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.'
如果我这样做,我仍然无法从该线程访问UI元素,甚至使用委托方法,例如;
If I do, I still can't access UI elements from this thread, even with delegate methods, such as;
Private main As Main
Private item As ListViewItem
Public Sub New(main As Main, ByRef item As ListViewItem, ip As String, set_provisioning_string As Boolean)
Me.main = main
Me.item = item
Dim t As New Threading.Thread(AddressOf go)
t.Start(New Object() {ip, set_provisioning_string})
End Sub
Private Sub go(o As Object)
...
...
Main.set_subitem_text(item, 4, "Checking something...")
...
...
Private Delegate Sub set_subitem_text_delegate(ByRef item As ListViewItem, index As Integer, text As String)
Public Sub set_subitem_text(ByRef item As ListViewItem, index As Integer, text As String)
If InvokeRequired Then
Invoke(New set_subitem_text_delegate(AddressOf set_subitem_text), item, index, text)
Else
item.SubItems(index).Text = text
End If
End Sub
那么有没有办法用分配的WebBrowser创建一个线程,该线程可以访问UI元素?
我尝试过:
ApartmentMode STA
非STA
使用代表
不使用委托
So is there any way to create a thread with an allocated WebBrowser, where that thread can access UI elements?
What I have tried:
ApartmentMode STA
Not STA
Using delegates
Not using delegates
推荐答案
您无法为WebBrowser控件创建单独的线程。它只是不起作用。
您可以为这些控件创建线程,但每个线程都必须创建自己的Form,并在其上创建WebBrowser控件。没有表单,控件将无法工作。
您使用WebBrowser控件的是什么?看起来你只是用它们来进行网页抓取,以便将一些数据放入ListView中。使用WebBrowser控件有点像矫枉过正。
You can't create separate threads for the WebBrowser controls. It just will not work.
You can create your threads for these controls, but each thread has to create it's own Form with a WebBrowser control on it. The control will not work without the Form.
What are you using the WebBrowser controls for? It seems like you're just using them to do web scraping to get some data to put in a ListView. Using a WebBrowser control is a bit overkill something like this.
这篇关于Web浏览器控制在不同的线程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!