2017-08-31 29 views
3

我想从192.168.1.1来ping 192.168.1.255到跳到下一个迭代,如果它需要太多的时间C#

于是我就用

FOR(i=1;i<=255;i++) 

//each time, I test the IP address by pinging it with the following code 

try { 

PingReply reply = pinger.Send(AdresaIp); 
pingable = reply.Status == IPStatus.Success; 

} 

catch (PingException) 

{ 

    // Discard PingExceptions and return false; 

} 

,我遇到的是这个问题:

PingReply reply = pinger.Send(AdresaIp); 

pingable = reply.Status == IPStatus.Success; 

当平从上方成功两个线具有2毫秒的执行时间,但是当它失败(巫会发生多次)它需要大约3秒,女巫是巨大的,如果我平255级的IP。

所以我想实现以下方式定时器:

if (timer > 1 second) continue; 
    //if it takes more than 1 second for the current iteration jump to the next 

迭代。

我尝试了System.Diagnostics.Stopwatch.StartNew(),doesen't没有为我工作,因为它给了我的时间后,ping测试。 我需要一些东西,可以让我检查ping测试是否正常工作,所以在达到1秒钟的时候,我可以使用CONTINUE命令。

感谢,

弗拉德

+2

'pinger'类型是什么? – mjwills

+0

Ping pinger = new Ping(); –

+1

您可能还想考虑使用https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-for-loop。 – mjwills

回答

5

您可以只使用Ping.Send Method (IPAddress, Int32) 。第二个参数是一个超时:

超时

类型:System.Int32

,指定的最大毫秒数(发送回声消息之后)

一个Int32值等待ICMP回应回复消息。

+0

谢谢,我只需要添加“,1000”:D –