VB.net简单多线程 [英] VB.net Simple Multithreading
问题描述
我有一个Private Sub Fill(),我试图从button1以
I have a Private Sub Fill(), which im trying to call from button1, in the form of
Dim t1 As System.Threading.Thread = New System.Threading.Thread(AddressOf Me.Fill)
t1.Start()
但是,当我运行程序时,什么也没发生.我多次单击该按钮,但该功能未执行.是什么赋予了? Fill函数基本上是从IE将一堆html输出到文本框中,运行正则表达式并将结果输出到列表框中.
However, when I run the program nothing happens. I click the button numerous times and the function isnt being executed. What gives? The Fill function is basically a outputting bunch of html from IE into a textbox, running regex and outputting the results in a listbox.
有人可以帮助我完成这项工作吗?非常感谢您的帮助. 编辑:下面是我要开始使用的Fill函数.当我尝试不使用多线程时,该函数本身可以工作.但是没有...
Can anyone help me get this working? I'd appreciate the help. Below, is the Fill function that I am trying to get working. The function itself works, when i try it without multithreading. But not with it...
Private Sub Fill()
Try
For Each links In ListBox2.Items
Dim blah As Boolean = False
Do While blah = False
Application.DoEvents()
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
blah = True
WebBrowser1.Navigate(links)
Application.DoEvents()
Me.Refresh()
'OUTPUT THE REGEX IN RTB
Try
RichTextBox1.Text = WebBrowser1.Document.Body.OuterHtml
RichTextBox1.Update()
Application.DoEvents()
Me.Refresh()
'INTRODUCE REGEX
If CheckBox1.Checked = True Then
Dim R As New Regex("</H3><.*gt;")
For Each M As Match In R.Matches(RichTextBox1.Text)
Dim email As String = M.Value.Substring(9).Split("&;").GetValue(0).ToString
ListBox1.Items.Add(email)
Next
End If
Catch ex As Exception
Label1.Text = "Error recieved. Program will not stop"
Me.Refresh()
End Try
Application.DoEvents()
Me.Refresh()
End If
Loop
Next
Catch ex As Exception
End Try
End Sub
推荐答案
我认为您遇到了问题,因为当您尝试在Fill()方法中写入文本框时,您不在UI线程上–这将导致一个例外.要解决该问题,您需要使用 BeginInvoke 和一个委托切换到UI线程,如下例所示:
I think you are having problems because you are not on the UI thread when you are trying to write to the textbox in the Fill() method – this will causes an exception. To solve the problem you need to switch to the UI thread using BeginInvoke and a delegate as in the example below:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t1 As System.Threading.Thread = New System.Threading.Thread(AddressOf Me.Fill)
t1.Start()
End Sub
Private Delegate Sub FillDelegate()
Private Sub Fill()
If TextBox1.InvokeRequired Then
TextBox1.BeginInvoke(New FillDelegate(AddressOf Fill))
Else
TextBox1.Text = "Worked!!!!"
End If
End Sub
这篇关于VB.net简单多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!