为什么我的VB.NET htmlelementcollection代码在线程中使用时会抛出强制转换错误?

时间:2012-11-03 11:52:32

标签: vb.net multithreading

我在VB.NET中编写了一些代码,它根据'alt'属性'抓取'图像的src / URL。它在某些网站上运行得很好,但在其他网站上它需要线程 - 等到图像加载后,因为图像在DocumentCompleted发生时没有加载。

我的问题是,当我的代码与线程一起使用时,我收到invalidcastexception错误。

这是我的代码,以及发生错误的位置:

Private Sub WB1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WB1.DocumentCompleted
    urlBox.Text = e.Url.ToString()

    If urlBox.Text = "URL_GOES_HERE"
        Dim success As Integer = site.fill() 'calls another function, returns 1 on success
        If success = 1 Then
            Dim captchaThread As New Thread(New ThreadStart(AddressOf getCaptchaURL))
            captchaThread.Start()
        End If
    End If
End Sub

Public Function getCaptchaURL()
    Thread.Sleep(5000) 'Tell thread to sleep so images can load
    Dim URL As String
    Dim images As HtmlElementCollection = WB1.Document.GetElementsByTagName("img") 'This is where I get the 'invalidcastexception' error
    For Each element As HtmlElement In images
        Dim source As String = element.GetAttribute("alt").ToString
        If source = "CAPTCHA Image" Then
            URL = element.GetAttribute("src")
            MessageBox.Show(URL) 'Show URL to check the source has been grabbed
        End If
    Next
    Return URL 'Return URL for further functions
End Function

因此,澄清一下,这段代码:Dim images As HtmlElementCollection = WB1.Document.GetElementsByTagName("img")在与线程一起使用时给出了一个错误,但在线程中没有使用时却没有。

1 个答案:

答案 0 :(得分:0)

该行

For Each element As HtmlElement In images
需要重写

以避免遇到类型转换的问题。

尝试以下方法:

For Each element In images
   If TypeOf(element) Is HtmlElement Then

         'the rest of your code goes here

   End If
Next