【发布时间】:2021-05-19 01:51:00
【问题描述】:
给定一个 IP 地址列表:
List<string> ipList = new List<string>(); //example: 192.168.0.1, 192.168.0.2, 192.168.0.3 etc.
我正在尝试以并行方式遍历列表中的每个 IP,然后在屏幕上打印一条有意义的消息:
foreach (PingReply pingReply in ipList.AsParallel().WithDegreeOfParallelism(64).Select(ip => new Ping().Send(ip)))
{
Console.WriteLine($"Ping status: {pingReply.Status} for the target IP address: {ip}");
}
在这种情况下,我无法访问 ip。我真的很想了解在发送它们时如何访问每个 relative ip?
我已经探索了PingReply 对象,但以PingReply.Address 为例,它包含主机(发件人)IP,因此无法满足此要求。我真的希望 PingReply 对象包含被 ping 的 Ip!
更新
根据@haim770 和@MindSwipe 提供的示例,我最终使用了:
foreach (var pingResponseData in ipList.AsParallel().WithDegreeOfParallelism(64).Select(ip => new { ip, pingReply = new Ping().Send(ip) }))
{
Console.WriteLine($"Ping status: {pingResponseData.pingReply.Status} for the target IP address: {pingResponseData.ip}");
}
更新 2
根据@pinkfloydx33 关于使用ValueTuple 的评论,我已按照以下示例完成:
foreach (var (ip, reply) in ipList.AsParallel().WithDegreeOfParallelism(ipList.Count).Select(ip => (ip, new Ping().Send(ip, 150))))
{
Console.WriteLine($"Ping status: {reply.Status} for the target IP address: {ip}");
}
【问题讨论】:
-
只需使用
.Select(ip => new { ip, pingResult = new Ping().Send(ip) }) -
改用
Parallel.ForEach(ipList, ip => { /*code to do ping and write result*/ });。它会更容易阅读。 -
谢谢@haim770!您的回应是有道理且有效的。