【发布时间】:2019-03-05 08:34:10
【问题描述】:
我的代码有问题,运行速度很慢
我的代码:
private static void PortRangeScan()
{
Console.Clear();
var From = FROM.Split('.'); // example (103.218.27.85)
string From1 = From[0];
string From2 = From[1];
string From3 = From[2];
string From4 = From[3];
var To = TO.Split('.'); // example (123.218.27.85)
string To1 = To[0];
string To2 = To[1];
string To3 = To[2];
string To4 = To[3];
for (int CurrentProxy = int.Parse(From1); CurrentProxy <= int.Parse(To1); CurrentProxy++)
{
foreach (int s in Ports)
{
TcpClient Scan = new TcpClient();
try
{
// If there is no exception then the Port is open
Scan.Connect($"{CurrentProxy}.{From2}.{From3}.{From4}", s);
Console.WriteLine($"[{CurrentProxy}.{From2}.{From3}.{From4}] | [{s}] | OPEN", Color.Green);
}
catch
{
// If there is an excpetion then it means the Port is closed
Console.WriteLine($"[{CurrentProxy}.{From2}.{From3}.{From4}] | [{s}] | CLOSED", Color.Red);
}
}
}
}
这段代码运行速度很慢,如果端口关闭,它可能需要长达 10 秒才能检查下一个端口。
我想添加一个 Parallel.For 循环或多线程,但我不确定如何使用此代码来实现。 那我需要什么:
如何使这段代码更快,或者如何添加多线程
【问题讨论】:
标签: c# multithreading performance port