Link to home
Start Free TrialLog in
Avatar of rbichon
rbichon

asked on

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?
Avatar of ZeonFlash
ZeonFlash

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.
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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"...
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
Avatar of rbichon

ASKER

Thanks. That worked great!