whipped up this code real quick which uses a ThreadPool on Form Load to iterate through my subnet and tell me if there's a device communicating at each IP address.
Works great.
some questions:
Why am I able to update BOTH my label at the top AND the listbox, but I'm only using an .Invoke on the Listbox?
How can I know how many threads are currently being used while that is executing?
What does the SyncLock do?
I'm aware some people don't like the use of Application.DoEvents(). Is it ok to be using it in this instance or is there a better practice?
For those wanting to try it out, drag a Label and a Listbox to a new form. Label is called "currentIPTextbox", Listbox is default name.
vb.net Code:
Imports System.Threading
Public Class Form1
Private Elem As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListBox1.Items.Clear()
ThreadPool.QueueUserWorkItem(AddressOf Initialize)
End Sub
Private Sub Add()
Dim pingresult As String
pingresult = My.Computer.Network.Ping("192.168.1." & Elem, 200)
ListBox1.Items.Add("192.168.1." & Elem & " : " & pingresult)
currentIPTextbox.Text = "192.168.1." & Elem
Application.DoEvents()
End Sub
Private Sub Initialize(ByVal State As Object)
Dim I As Long
SyncLock ListBox1.GetType
For I = 1 To 255
Elem = I
ListBox1.Invoke(CType(AddressOf Add, MethodInvoker))
Next
End SyncLock
End Sub
End Class