0

问题是多线程无法正常工作以从 webbrowser1.document.links 获取链接。我怎么解决这个问题?

Public Class Form1


Dim thread1 As System.Threading.Thread

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    thread1 = New System.Threading.Thread(AddressOf GetLinks)
    thread1.Start()

End Sub
Private Sub GetLinks()
    For i As Integer = 0 To WebBrowser1.Document.Links.Count - 1
        If TextBox1.Text.Length > 0 Then
            TextBox1.Text += Environment.NewLine & WebBrowser1.Document.Links(i).ToString
        Else
            TextBox1.Text = WebBrowser1.Document.Links(i).ToString

        End If
    Next
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    WebBrowser1.Navigate("www.google.com")
    Me.CheckForIllegalCrossThreadCalls = False

End Sub
End Class
4

1 回答 1

0

您不能从窗体主线程以外的另一个线程调用窗体上的控件之一(在本例中为 TextBox1 和 WebBrowser1)。您需要使用委托。

这可以解决问题:

  Private _iLinks As Integer

    Dim thread1 As System.Threading.Thread

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        CheckForIllegalCrossThreadCalls = False
        _iLinks = WebBrowser1.Document.Links.Count
        thread1 = New System.Threading.Thread(AddressOf GetLinks)
        thread1.Start()
    End Sub

    Private Sub GetLinks()
        For i As Integer = 0 To _iLinks - 1
             UpdateTextBoxDelegate(i)             
        Next
    End Sub

    Private Sub UpdateTextBox(ByVal iLink As Integer)
        If TextBox1.Text.Length > 0 Then
            TextBox1.Text += Environment.NewLine & WebBrowser1.Document.Links(iLink).ToString
        Else
            TextBox1.Text += WebBrowser1.Document.Links(iLink).InnerText.ToString()
        End If
    End Sub

    Private Delegate Sub UpdateTextBoxCallback(ByVal iLink As Integer)

    Private Sub UpdateTextBoxDelegate(ByVal iLink As Integer)
        Try
            If Me.InvokeRequired Then
                Dim cb As New UpdateTextBoxCallback(AddressOf UpdateTextBox)
                Me.Invoke(cb, New Object() {iLink})
            Else
                UpdateTextBox(iLink)
            End If
        Catch ex As Exception
            MessageBox.Show("There was an error " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        WebBrowser1.Navigate("http://stackoverflow.com/")
    End Sub
于 2013-07-13T01:47:38.587 回答