When we need to connect to hundreds or thousands of remote computers, we can try to use
Parallel.ForEach. But it is the wrong way because it will take too many resources. Another mistake is to use "
For (Each) ... Next" because it's too long.
While optimizing my code, I found a perfect solution which helped me to connect to more than 262144 remote IPs in an extremely short period of time. Check it out:
Public Class toTcpClient
Public tmr As System.Threading.Timer
Public id As String = ""
Public Event TimeoutReached(ByVal sender As toTcpClient)
Public Sub BeginConnectWithTimeout(ByVal host As String,
ByVal port As Integer,
ByVal ConnectCallback As System.AsyncCallback,
Optional ByVal timeout As Integer = 100)
BeginConnect(host, port, ConnectCallback, Me)
tmr = New Threading.Timer(AddressOf toTcpClient_TimeoutReached, _
Nothing, timeout, System.Threading.Timeout.Infinite)
Private Sub toTcpClient_TimeoutReached(ByVal e As Object)
Now you can create an effective procedure to connect through
[For...Next]. So, if
tcpClient connected successfully, first of all turn off
Timer object using
Dispose. Else, you should close