Getting Faster result on Ping in C#

空扰寡人 提交于 2019-12-14 03:58:45

问题


I'm making a tool to test a connection to certain host using a class "PingReply" in .NET. My problem is it takes a while to get a result if the ping result is a fail. It is LAN environment so i can already assume that the connection is failed if it takes more than 100ms. The code below shows a result after 5 seconds, which is 5000ms, if the connection to the host fails. Can i get the faster result even though the connection is failed?

Ping x = new Ping();
PingReply reply = x.Send(IPAddress.Parse("192.168.0.1")); 
if (reply.Status == IPStatus.Success)
{
    //Do something
}

回答1:


You can pass a timeout to the Ping.Send() method. Please check out the overloaded members.




回答2:


Since we can't see your ping object, ill assume you don't know about TIMEOUT. I usually send an async ping, and set the timeout to 3 seconds.

 try
            {
                Ping ping = new Ping();
                ping.PingCompleted += (sender, e) =>
                {
                    if (e.Reply.Status != IPStatus.Success)
                        // Report fail
                    else                    
                       // Report success

                };
                ping.SendAsync(target, 3000, target); // Timeout is 3 seconds here
            }
            catch (Exception)
            {
                return;
            }



回答3:


Ping.Send() has an overload with a timeout parameter:

PingReply reply = x.Send(IPAddress.Parse("192.168.0.1"), 100);



回答4:


You could use an async delegate to kick off the Ping. The async delegate has a function called BeginInvoke that will kick off a background thread that will immediately return a IAsyncResult. The IAsyncResult has a wait handler called AsyncWaitHandle which has a method called WaitOne which can be assigned a time to wait. This will freeze the current thread a given time in milliseconds, in your case 100, then you can use the property IsCompleted to check to see if the thread has completed its work. For Example:

Func<PingReply>  pingDelegate = () => new Ping().Send(IPAddress.Parse("192.168.0.1"));

IAsyncResult result = pingDelegate.BeginInvoke(r => pingDelegate.EndInvoke(r), null);

//wait for thread to complete
result.AsyncWaitHandle.WaitOne(100);

if (result.IsCompleted)
{
    //Ping Succeeded do something
    PingReply reply = (PingReply) result;

    //Do something with successful reply
}


来源:https://stackoverflow.com/questions/14361295/getting-faster-result-on-ping-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!