Results 1 to 10 of 10

Thread: Not Connecting to website in New Thread

  1. #1

    Thread Starter
    New Member
    Join Date
    Jul 2011
    Posts
    10

    Not Connecting to website in New Thread

    I have hit a road bump. I have been piecing together bits of code that I have found and customized it to work with my app. Now the following code works find out of a separate thread, but as soon as I put it into its on threads it doesn't want to connect.

    Any suggestions?


    Code:
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    
    
    
    
            getAlexaNow = New Thread(AddressOf ThreadTask)
            getAlexaNow.IsBackground = True
            getAlexaNow.Start()
    
    
        End Sub
        Private Sub ThreadTask()
            Dim intList As Integer
            Dim strAlexa As String
    
            intList = "0"
            strSearch = txtSearch.Text
    
    
            Do Until intList = linksList.Items.Count
    
                Dim linkUrl As String = "http://www.alexa.com/search?q=" & linksList.Items.Item(intList)
                Try
                    Dim myResponse As Net.HttpWebResponse = Net.HttpWebRequest.Create(linkUrl).GetResponse '// connect.
                    Dim myStream As IO.Stream = myResponse.GetResponseStream() '// get.
                    Dim myReader As New IO.StreamReader(myStream) '// read.
                    Dim myWebFileInfo As String = myReader.ReadToEnd '// get innerHtml of Page.
                    myReader.Close() : myStream.Close() : myResponse.Close() '// close reader, information stream, and connection.
    
    
                    RichTextBox3.Text = myWebFileInfo
    
    
    
                    If InStr(myWebFileInfo, "No regional data") Then
                        alexaList.Items.Add((linksList.Items.Item(intList)) & ":" & "No Alexa rank")
                        Exit Try
                    End If
    
                    '// get location of <pre> by index.
                    Dim myStartIndex As Integer = myWebFileInfo.IndexOf(">US</a>:") + 8 '// add +5 to not add "<pre>" to final result.
                    '// get location of </pre> by index.
                    Dim myEndIndex As Integer = myWebFileInfo.IndexOf("          </li>")
                    '// subtract to get a total number for the substring length result.
                    Dim myStringLengthToExtract As Integer = myEndIndex - myStartIndex
                    '// display result.
                    strAlexa = myWebFileInfo.Substring(myStartIndex, myStringLengthToExtract)
                    If InStr(strAlexa, "XHTML") Then
                        alexaList.Items.Add((linksList.Items.Item(intList)) & ":" & "No Alexa rank")
    
                    Else
                        If InStr(strAlexa, "%%") Then
    
                        Else
    
                            alexaList.Items.Add((linksList.Items.Item(intList)) & ":" & strAlexa)
                        End If
                    End If
                Catch ex As Exception
                    MsgBox("Connection Error.", MsgBoxStyle.Critical, "myCool Error Message")
                End Try
    
                intList = intList + 1
            Loop
        End Sub

  2. #2
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Not Connecting to website in New Thread

    If you are using a control on a thread that is different from the one it was created upon, you will usually get an exception. ie. alexaList.Items.Add

    You must do all work for a control on the thread it was created upon.

    To add, this line here: Catch ex As Exception, tells you what the problem is, you are actually ignoring it. It tells you the real problem. Use this instead of your existing MsgBox.

    Code:
    MessageBox.Show("Connection Error - " & ex.Message)

  3. #3

    Thread Starter
    New Member
    Join Date
    Jul 2011
    Posts
    10

    Re: Not Connecting to website in New Thread

    Quote Originally Posted by Grimfort View Post
    If you are using a control on a thread that is different from the one it was created upon, you will usually get an exception. ie. alexaList.Items.Add

    You must do all work for a control on the thread it was created upon.

    To add, this line here: Catch ex As Exception, tells you what the problem is, you are actually ignoring it. It tells you the real problem. Use this instead of your existing MsgBox.

    Code:
    MessageBox.Show("Connection Error - " & ex.Message)

    Ok great! Thanks so much for your response.


    This is the detailed error message.
    Code:
    Connection error - crosss-thread operation not valid: Control 'alexList' accessed from a thread other than the thread it was created on.
    I'm wondering what I have to change because alexaList is a simlpe list box.

    Here is my entire code.


    Code:
    Imports System.Text.RegularExpressions
    Imports System.Net
    Imports System.Text
    Imports System.Threading
           
    Public Class Form1
    
        Private Property str33 As Object
        Dim strNum As Integer
        Dim strSearch As String
        Private getAlexaNow As Thread
    
    
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            ' Dim linkurl As String
    
            'linkurl = "http://www.860designs.com/check.txt"
            ' Dim myResponse As Net.HttpWebResponse = Net.HttpWebRequest.Create(linkUrl).GetResponse '// connect.
            '' Dim myStream As IO.Stream = myResponse.GetResponseStream() '// get.
            ' Dim myReader As New IO.StreamReader(myStream) '// read.
            ' Dim myWebFileInfo As String = myReader.ReadToEnd '// get innerHtml of Page.
            ' Dim strUser As String
    
    
            '// close reader, information stream, and connection.
            ' myReader.Close() : myStream.Close() : myResponse.Close()
    
            ' strUser = InputBox("username")
            ' If InStr(myWebFileInfo, strUser) Then
    
            '  Else
            '  Me.Close()
            '   Exit Sub
    
            '  End If
        End Sub
    
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
           
            WebBrowser1.Navigate("http://www.google.com/search?tbm=blg&hl=en&source=hp&biw=&bih=&q=" & strSearch & "&btnG=Search")
            
            strNum = 1
            strNum = 10
            tmrBroswer.Enabled = True
    
        End Sub
    
    
        Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
    
    
            'For every link in the current document...         
            For Each ele As HtmlElement In WebBrowser1.Document.Links
                'Get whatever text there is in the 'href' attribute
                Dim eletarget As String = ele.GetAttribute("href")
                Dim eletargetNew As String
                'Add it to the listbox
    
                If InStr(eletarget, "google.com") Then
                ElseIf InStr(eletarget, "youtube.com") Then
                ElseIf InStr(eletarget, "wdyl.com") Then
                ElseIf InStr(eletarget, "javascript") Then
                Else
    
                    Dim myStartIndex As Integer = eletarget.IndexOf("h") + 1 '// add +5 to not add "<pre>" to final result.
                    '// get location of </pre> by index.
                    Dim myEndIndex As Integer = eletarget.IndexOf("com") + 3
                    '// subtract to get a total number for the substring length result.
                    Dim myStringLengthToExtract As Integer = myEndIndex - myStartIndex
                    '// display result.
                    eletargetNew = eletarget.Substring(myStartIndex, myStringLengthToExtract)
    
                    If eletargetNew = "t" Then
    
                    Else
    
                        linksList.Items.Add("h" & eletargetNew)
                    End If
                End If
    
                'Carry on to the next link
            Next
            'strNum = strNum + 10
            ' Dim strSearch As String
            ' strSearch = txtSearch.Text
            ' If strNum > 100 Then
            'Exit Sub
            ' End If
            If tmrBroswer.Enabled = False Then
                tmrBroswer.Enabled = False
                Exit Sub
    
            End If
    
            tmrBroswer.Enabled = True
    
    
    
        End Sub
    
    
        Private Sub tmrBroswer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmrBroswer.Tick
            Dim intStop As Integer
            strSearch = txtSearch.Text
    
            If intStop >= 5 Then
    
                Exit Sub
                tmrBroswer.Enabled = False
            End If
            WebBrowser1.Navigate("http://www.google.com/search?tbm=blg&hl=en&source=hp&biw=&bih=&q=" & strSearch & "&btnG=Search&start=" & strNum)
    
            intStop = intStop + 1
            strNum = strNum + 10
        End Sub
    
        Private Sub cmdStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStop.Click
            tmrBroswer.Enabled = False
        End Sub
    
    
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    
    
    
    
            getAlexaNow = New Thread(AddressOf ThreadTask)
            getAlexaNow.IsBackground = True
            getAlexaNow.Start()
    
    
        End Sub
        Private Sub ThreadTask()
            Dim intList As Integer
            Dim strAlexa As String
    
            intList = "0"
            strSearch = txtSearch.Text
    
    
            Do Until intList = linksList.Items.Count
    
                Dim linkUrl As String = "http://www.alexa.com/search?q=" & linksList.Items.Item(intList)
                Try
                    Dim myResponse As Net.HttpWebResponse = Net.HttpWebRequest.Create(linkUrl).GetResponse '// connect.
                    Dim myStream As IO.Stream = myResponse.GetResponseStream() '// get.
                    Dim myReader As New IO.StreamReader(myStream) '// read.
                    Dim myWebFileInfo As String = myReader.ReadToEnd '// get innerHtml of Page.
                    myReader.Close() : myStream.Close() : myResponse.Close() '// close reader, information stream, and connection.
    
    
    
                    If InStr(myWebFileInfo, "No regional data") Then
                        alexaList.Items.Add((linksList.Items.Item(intList)) & ":" & "No Alexa rank")
                        Exit Try
                    End If
    
                    '// get location of <pre> by index.
                    Dim myStartIndex As Integer = myWebFileInfo.IndexOf(">US</a>:") + 8 '// add +5 to not add "<pre>" to final result.
                    '// get location of </pre> by index.
                    Dim myEndIndex As Integer = myWebFileInfo.IndexOf("          </li>")
                    '// subtract to get a total number for the substring length result.
                    Dim myStringLengthToExtract As Integer = myEndIndex - myStartIndex
                    '// display result.
                    strAlexa = myWebFileInfo.Substring(myStartIndex, myStringLengthToExtract)
                    If InStr(strAlexa, "XHTML") Then
                        alexaList.Items.Add((linksList.Items.Item(intList)) & ":" & "No Alexa rank")
    
                    Else
                        If InStr(strAlexa, "%%") Then
    
                        Else
    
                            alexaList.Items.Add((linksList.Items.Item(intList)) & ":" & strAlexa)
                        End If
                    End If
                Catch ex As Exception
                    MsgBox("Connection Error - " & ex.Message)
                End Try
    
                intList = intList + 1
            Loop
        End Sub
    
    
        Private Sub alexaList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles alexaList.SelectedIndexChanged
    
            Dim aLink As String
            Dim aLinkNew As String
            aLink = alexaList.SelectedItem.ToString
    
            Dim myStartIndex As Integer = aLink.IndexOf("h") + 1 '// add +5 to not add "<pre>" to final result.
            '// get location of </pre> by index.
            Dim myEndIndex As Integer = aLink.IndexOf("com") + 3
            '// subtract to get a total number for the substring length result.
            Dim myStringLengthToExtract As Integer = myEndIndex - myStartIndex
            '// display result.
            aLinkNew = aLink.Substring(myStartIndex, myStringLengthToExtract)
    
            If aLinkNew = "t" Then
    
            Else
    
                alexaBrowser.Navigate("h" & aLinkNew)
            End If
    
        End Sub
    
    
    
    
    
    End Class

  4. #4
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Not Connecting to website in New Thread

    So the exception tells you that you are trying to change a control on a different thread then the one it was created upon .

    Here is an example on how to start doing this here, or you could use an extension (advanced, but makes it easier after).

  5. #5

    Thread Starter
    New Member
    Join Date
    Jul 2011
    Posts
    10

    Re: Not Connecting to website in New Thread

    Quote Originally Posted by Grimfort View Post
    So the exception tells you that you are trying to change a control on a different thread then the one it was created upon .

    Here is an example on how to start doing this here, or you could use an extension (advanced, but makes it easier after).


    Thank you so much for all of your help. I have taken a look at the thread, but couldn't be more confused.

    I will review it again, but I fear this may cause me to hit a road block.

  6. #6
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Not Connecting to website in New Thread

    Do not be too worried. Instead of directly using threads, M$ have created the BackgroundWorker control that can do most of this stuff for you. It has special events where you can access controls without this error.

  7. #7

    Thread Starter
    New Member
    Join Date
    Jul 2011
    Posts
    10

    Re: Not Connecting to website in New Thread

    Quote Originally Posted by Grimfort View Post
    Do not be too worried. Instead of directly using threads, M$ have created the BackgroundWorker control that can do most of this stuff for you. It has special events where you can access controls without this error.
    Ok great! I will definetly read into the M$ solution. Thanks for all of your help!

  8. #8

    Thread Starter
    New Member
    Join Date
    Jul 2011
    Posts
    10

    Re: Not Connecting to website in New Thread

    I have moved my task into a background worker sub, but I am still having the same error.


    Code:
    Imports System.Text.RegularExpressions
    Imports System.Net
    Imports System.Text
    Imports System.Threading
           
    Public Class Form1
    
        Private Property str33 As Object
        Dim strNum As Integer
        Dim strSearch As String
        Private getAlexaNow As Thread
    
    
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            ' Dim linkurl As String
    
            'linkurl = "http://www.860designs.com/check.txt"
            ' Dim myResponse As Net.HttpWebResponse = Net.HttpWebRequest.Create(linkUrl).GetResponse '// connect.
            '' Dim myStream As IO.Stream = myResponse.GetResponseStream() '// get.
            ' Dim myReader As New IO.StreamReader(myStream) '// read.
            ' Dim myWebFileInfo As String = myReader.ReadToEnd '// get innerHtml of Page.
            ' Dim strUser As String
    
    
            '// close reader, information stream, and connection.
            ' myReader.Close() : myStream.Close() : myResponse.Close()
    
            ' strUser = InputBox("username")
            ' If InStr(myWebFileInfo, strUser) Then
    
            '  Else
            '  Me.Close()
            '   Exit Sub
    
            '  End If
        End Sub
    
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
           
            WebBrowser1.Navigate("http://www.google.com/search?tbm=blg&hl=en&source=hp&biw=&bih=&q=" & strSearch & "&btnG=Search")
            
            strNum = 1
            strNum = 10
            tmrBroswer.Enabled = True
    
        End Sub
    
    
        Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
    
    
            'For every link in the current document...         
            For Each ele As HtmlElement In WebBrowser1.Document.Links
                'Get whatever text there is in the 'href' attribute
                Dim eletarget As String = ele.GetAttribute("href")
                Dim eletargetNew As String
                'Add it to the listbox
    
                If InStr(eletarget, "google.com") Then
                ElseIf InStr(eletarget, "youtube.com") Then
                ElseIf InStr(eletarget, "wdyl.com") Then
                ElseIf InStr(eletarget, "javascript") Then
                Else
    
                    Dim myStartIndex As Integer = eletarget.IndexOf("h") + 1 '// add +5 to not add "<pre>" to final result.
                    '// get location of </pre> by index.
                    Dim myEndIndex As Integer = eletarget.IndexOf("com") + 3
                    '// subtract to get a total number for the substring length result.
                    Dim myStringLengthToExtract As Integer = myEndIndex - myStartIndex
                    '// display result.
                    eletargetNew = eletarget.Substring(myStartIndex, myStringLengthToExtract)
    
                    If eletargetNew = "t" Then
    
                    Else
    
                        linksList.Items.Add("h" & eletargetNew)
                    End If
                End If
    
                'Carry on to the next link
            Next
            'strNum = strNum + 10
            ' Dim strSearch As String
            ' strSearch = txtSearch.Text
            ' If strNum > 100 Then
            'Exit Sub
            ' End If
            If tmrBroswer.Enabled = False Then
                tmrBroswer.Enabled = False
                Exit Sub
    
            End If
    
            tmrBroswer.Enabled = True
    
    
    
        End Sub
    
    
        Private Sub tmrBroswer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmrBroswer.Tick
            Dim intStop As Integer
            strSearch = txtSearch.Text
    
            If intStop >= 5 Then
    
                Exit Sub
                tmrBroswer.Enabled = False
            End If
            WebBrowser1.Navigate("http://www.google.com/search?tbm=blg&hl=en&source=hp&biw=&bih=&q=" & strSearch & "&btnG=Search&start=" & strNum)
    
            intStop = intStop + 1
            strNum = strNum + 10
        End Sub
    
        Private Sub cmdStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStop.Click
            tmrBroswer.Enabled = False
        End Sub
    
    
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    
    
    
    Me.BackgroundWorker1.RunWorkerAsync()
    
    
        End Sub
    
    
        Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, _
                                         ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Dim worker As System.ComponentModel.BackgroundWorker = DirectCast(sender, System.ComponentModel.BackgroundWorker)
    
            For i As Integer = 1 To 100
                'Raise the ProgressChanged event in the UI thread.
                worker.ReportProgress(i, i & " iterations complete")
    
                Dim intList As Integer
                Dim strAlexa As String
    
                intList = "0"
                strSearch = txtSearch.Text
    
    
                Do Until intList = linksList.Items.Count
    
                    Dim linkUrl As String = "http://www.alexa.com/search?q=" & Me.linksList.Items.Item(intList)
                    Try
                        Dim myResponse As Net.HttpWebResponse = Net.HttpWebRequest.Create(linkUrl).GetResponse '// connect.
                        Dim myStream As IO.Stream = myResponse.GetResponseStream() '// get.
                        Dim myReader As New IO.StreamReader(myStream) '// read.
                        Dim myWebFileInfo As String = myReader.ReadToEnd '// get innerHtml of Page.
                        myReader.Close() : myStream.Close() : myResponse.Close() '// close reader, information stream, and connection.
    
    
    
                        If InStr(myWebFileInfo, "No regional data") Then
                            Me.alexaList.Items.Add((Me.linksList.Items.Item(intList)) & ":" & "No Alexa rank")
                            Exit Try
                        End If
    
                        '// get location of <pre> by index.
                        Dim myStartIndex As Integer = myWebFileInfo.IndexOf(">US</a>:") + 8 '// add +5 to not add "<pre>" to final result.
                        '// get location of </pre> by index.
                        Dim myEndIndex As Integer = myWebFileInfo.IndexOf("          </li>")
                        '// subtract to get a total number for the substring length result.
                        Dim myStringLengthToExtract As Integer = myEndIndex - myStartIndex
                        '// display result.
                        strAlexa = myWebFileInfo.Substring(myStartIndex, myStringLengthToExtract)
                        If InStr(strAlexa, "XHTML") Then
                            Me.alexaList.Items.Add((Me.linksList.Items.Item(intList)) & ":" & "No Alexa rank")
    
                        Else
                            If InStr(strAlexa, "%%") Then
    
                            Else
    
                                Me.alexaList.Items.Add((Me.linksList.Items.Item(intList)) & ":" & strAlexa)
                            End If
                        End If
                    Catch ex As Exception
                        MsgBox("Connection Error - " & ex.Message)
                    End Try
    
                    intList = intList + 1
                Loop
                Threading.Thread.Sleep(250)
            Next i
        End Sub
    
        Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, _
                                                  ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
            Me.ProgressBar1.Value = e.ProgressPercentage
            Me.lblStatus.Text = TryCast(e.UserState, String)
        End Sub
    
        'This method is executed in the UI thread.
        Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, _
                                                         ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
            Me.lblStatus.Text = "Operation complete"
        End Sub
    
    
    
    
    
        Private Sub alexaList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    
            Dim aLink As String
            Dim aLinkNew As String
            aLink = alexaList.SelectedItem.ToString
    
            Dim myStartIndex As Integer = aLink.IndexOf("h") + 1 '// add +5 to not add "<pre>" to final result.
            '// get location of </pre> by index.
            Dim myEndIndex As Integer = aLink.IndexOf("com") + 3
            '// subtract to get a total number for the substring length result.
            Dim myStringLengthToExtract As Integer = myEndIndex - myStartIndex
            '// display result.
            aLinkNew = aLink.Substring(myStartIndex, myStringLengthToExtract)
    
            If aLinkNew = "t" Then
    
            Else
    
                alexaBrowser.Navigate("h" & aLinkNew)
            End If
    
        End Sub
    
    
    
    
    End Class
    Any suggestions?

  9. #9
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Not Connecting to website in New Thread

    Yes, read the documentation! Don't just read it, really read it! It has a note in bright yellow that specifically states:

    You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.
    All you have done is thrown your code into the DoWork method. You need to seperate out the links into a list/collection/array, then put the answers into another list/collection/array. When you are ready to .ReportProgress and then put the answers from the list into the controls on the form.

  10. #10
    PowerPoster
    Join Date
    Mar 2002
    Location
    UK
    Posts
    4,780

    Re: Not Connecting to website in New Thread

    The OP has sent me PM asking for more help, so I will repost in here some questions to help him/her out.

    In your DoWork method, this is the first time you use a control. The answer is you don't.

    Do Until intList = linksList.Items.Count
    Dim linkUrl As String = "http://www.alexa.com/search?q=" & Me.linksList.Items.Item(intList)


    Before you even start DoWork, you need to extract the data into a list:

    Code:
    Private Links As New Generic.List(Of String)
    
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    
       For Each strItem As String Me.linksList.Items
          Links.Add(strItem)
       Next
    
       Me.BackgroundWorker1.RunWorkerAsync()
    
    End Sub
    
    'Then in the DoWork you use the Links list not the control
    
    For Each strItem As String In Links
      .....
    Next

    Note, this is an example, you can use a string array instead of a List(Of) or you might use a queue instead, possibly you might use a Items.CopyTo. Different people use different methods depending on their use or preference.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width