I’ve made a port scanner in C#, but I can’t seem to make it go faster:
private void Scan()
{
int startPort = Convert.ToInt32(txtFrom.Text);
int endPoint = Convert.ToInt32(txtTo.Text);
progressBar1.Value = 0;
progressBar1.Maximum = endPoint - startPort + 1;
for (int currPort = startPort; currPort <= endPoint; currPort++)
{
TcpClient tcpportScan = new TcpClient();
tcpportScan.SendTimeout = 10;
try
{
tcpportScan.Connect(txtIPaddress.Text, currPort);
txtDisplay.AppendText("Port " + currPort + " open.\n");
}
catch (Exception)
{
txtDisplay.AppendText("Port " + currPort + " closed.\n");
}
progressBar1.PerformStep();
}
}
Does anyone know how to speed this process up?
The following C# 4 code will scan the ports in parallel and notify the UI whenever one of the scans completes.
Each scan is perfomed by the ScanSinglePortTask method, which starts a scan and returns a string result with the message to display. Each task starts with the LongRunning option to notify the runtime that running a lot of tasks in parallel is OK because each operation will take a long time.
After each scan a new task that runs on the UI thread will update the messages and the progress bar, by using TaskScheduler.FromCurrentSynchronizationContext.
The ToArray call is necessary to force enumeration of the LINQ query and start the tasks. The tasks array can be used with Task.Factory.ContinueWhenAll to run some other code after scanning finishes, eg. updating a busy indicator