使用Ping.SendAsync,如命令" ping -t"

时间:2015-07-30 18:51:39

标签: c# ping

我正在尝试使用ping.SendAsync ping主机。 现在我使用visual studio 2010和.net 4 我想ping指定的主机,直到我强行停止ping.SendAsync。 期望的结果就像我使用命令

ping -t host

现在我学习使用这里的例子:

https://msdn.microsoft.com/en-us/library/ms144962%28v=vs.110%29.aspx

但我无法找到该怎么做。

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
 public static void AsyncComplexLocalPing ()
    {
        // Get an object that will block the main thread.
        AutoResetEvent waiter = new AutoResetEvent (false);

        // Ping's the local machine.
        Ping pingSender = new Ping ();

        // When the PingCompleted event is raised, 
        // the PingCompletedCallback method is called.
        pingSender.PingCompleted += new PingCompletedEventHandler (PingCompletedCallback);

        IPAddress address = IPAddress.Loopback;

        // Create a buffer of 32 bytes of data to be transmitted. 
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes (data);

        // Wait 10 seconds for a reply. 
        int timeout = 10000;

        // Set options for transmission: 
        // The data can go through 64 gateways or routers 
        // before it is destroyed, and the data packet 
        // cannot be fragmented.
        PingOptions options = new PingOptions (64, true);

        // Send the ping asynchronously. 
        // Use the waiter as the user token. 
        // When the callback completes, it can wake up this thread.
        pingSender.SendAsync (address, timeout, buffer, options, waiter);

        // Prevent this example application from ending. 
        // A real application should do something useful 
        // when possible.
        waiter.WaitOne ();
        Console.WriteLine ("Ping example completed.");
    }

任何人都可以给我一个很好的提示,如何使ping.sendasynk继续发送数据包,直到我杀死程序/或我按一个键/或计时器终止它?我应该循环命令吗?提前谢谢。

1 个答案:

答案 0 :(得分:-2)

如果您不必担心异步运行查询,可以考虑使用.ContinueWith().Wait()并将ping方法置于循环中。这将使异步方法的行为类似于同步调用。伪代码:

        while(looping)
          {
            pingSender.SendAsync(params).ContinueWith((pingTask) =>
            {
                var responseMessage = pingTask.Result;
                if (goodResponse)
                {
                  doSomething
                }
            }).Wait(timeout);
          }