如果花费很多时间c#,请跳到下一次迭代

Vla*_*lad 3 c# ip loops ping timer

我想从192.168.1.1 ping到192.168.1.255

所以我用

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;

 }
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是:

PingReply reply = pinger.Send(AdresaIp);

pingable = reply.Status == IPStatus.Success;
Run Code Online (Sandbox Code Playgroud)

当ping成功时,上面的两行的执行时间为2毫秒,但是当它失败时(会发生多次)它需要大约3秒,如果我ping 255个IP,那就太大了.

所以我想以下列方式实现一个计时器:

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

迭代.

我试过了System.Diagnostics.Stopwatch.StartNew(,但是没有为我工作,因为它给了我测试ping之后的时间.我需要一些能让我检查ping测试工作的东西,所以当它达到1秒时,我可以使用CONTINUE命令.

谢谢,

弗拉德

Pik*_*koh 5

您可以使用Ping.Send方法(IPAddress,Int32) .第二个参数是超时:

超时

键入:System.Int32

一个Int32值,指定等待ICMP回送应答消息的最大毫秒数(发送回显消息之后).