Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parameter thread in vb

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

like image 215
tukangjam Avatar asked Sep 24 '26 15:09

tukangjam


1 Answers

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/

like image 99
WozzeC Avatar answered Sep 28 '26 05:09

WozzeC