Ping.Send(ip, timeout) in .Net returns too fast and complains on timeout

Viewed 11906

I'm using this method repeatedly in order to monitor connection to machine in the local network. When same test is done from cmd, results are steady and consistent:

C:\Windows\system32>ping -t 192.168.11.12

Pinging 192.168.11.12 with 32 bytes of data:
Reply from 192.168.11.12: bytes=32 time=1ms TTL=126
Reply from 192.168.11.12: bytes=32 time=1ms TTL=126

But when running from C# with 500 ms timeout it occasionally fails even before the timeout can expire:

public void TestIpAnswersPing()
{
    var ip = "192.168.11.12";
    var timeout = TimeSpan.FromMilliseconds(500);

    var p = new Ping();

    foreach (var i in Enumerable.Range(0, 1000))
    {
        var start = DateTime.Now;
        PingReply reply = p.Send(ip, (int)timeout.TotalMilliseconds);

        if(reply.Status != IPStatus.Success)
        {
            Debug.Assert(DateTime.Now - start >= timeout);
        }
    }
}

If I change timeout to 1 sec - all pass successfully with average time of pings 0.9 ms.

The only similar thing I have found is this - http://support.microsoft.com/kb/2533627, which doesn't help much.

Why this might happen and how to monitor high rate connection?

2 Answers

Just in case someone still has this issue: because of some reason, Thread.Sleep(50) indeed solves the problem.

Related