Passing variables to new threads

I want to start a new thread but I am getting an error.

Here is the code:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim ss As Thread = New Thread(AddressOf SendPing)
        ss.Start()
        ss = Nothing
    End Sub

Here is the sub:

    Sub SendPing(ByVal ip As String, ByVal index As Integer)
        'Code
    End Sub

How do I start a thread from a subroutine that requires certain variables to be passed to it?
LVL 1
rbichonAsked:
Who is Participating?
 
Bob LearnedCommented:
Here is a thought:

  Private Class ThreadWorker

    Public Sub New(ByVal url As String)
      m_url = url
    End Sub

    Private m_url As String = ""

    Public Sub SendPing()
    End Sub

  End Class

  Private Sub Ping(ByVal url As String)
    Dim worker As New ThreadWorker(url)
    Dim ss As New Thread(AddressOf worker.SendPing)
    ss.Start()
  End Sub

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Ping("www.google.com")
  End Sub

Bob
0
 
ZeonFlashCommented:
I found this article helpful when attempting to do the same thing:  http://www.devx.com/dotnet/Article/11358

What I ended up doing, though, was to set a global to the value that I needed, and then had the thread snag it upon starting.  Ofcourse, you should look into locking/unlocking the variables before doing that.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Threads can access anything in the object that contains them...be that a Form or a Class.  So make the variables global, either literally as ZeonFlash suggests by placing them in a Module, or by placing them at your Form level.

Or encapsulate your thread in a Class as Bob suggests so that the thread can access those values.  This is usually the preferred method since each thread can have its own set of "parameters"...
0
 
Bob LearnedCommented:
I have been reading a lot about thread local storage (TLS) and the ThreadStatic attribute, and they don't quite get the job done IMHO.  I love the encapsulation of a property and the thread Start method.

Bob
0
 
rbichonAuthor Commented:
Thanks. That worked great!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.