First of all, i don't have a good understanding about thread in vb, i tried to get info about it, but i'm still confused about how its work, addressof, the correct implementation and so on. I want to ask about how to create a new thread with parameter so i pass a value from the main thread. I try to do a loop and each loop create a new thread and do ping. Below is my code:
For i = 10 To 50
Dim worker As New Thread(New ThreadStart(Function()
My.Computer.Network.Ping("192.168.1." & i)
Console.WriteLine("192.168.1." & i)
End Function))
worker.Start()
Next
I realize this is wrong because the result will loop and ping the last value of variable i. So i want to ask about the correct suggestion about it. I will really appreciate if you add a simple explanation for me just to get a better understanding about thread.
Thank you in advance
Your code is almost correct. However, since you are using the same variable for all your created threads. So when your thread starts it more or less contains a pointer to i rather than the value of i. Which means that as your loop progress the value of i change. So when your threads actually start working the loop has completed and the value of i has changed to 51.
To resolve this you have to create a new integer inside the loop. So that the supplied object is unique for every loop. Like so:
Dim x as Integer = i
Then supply x instead of i to the Thread and you are all set.
Here is some reading on the topic: https://devblogs.microsoft.com/vbteam/closures-in-vb-part-5-looping/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With