【问题标题】:Use Ping.SendAsync like the command "ping -t"像命令“ping -t”一样使用 Ping.SendAsync
【发布时间】:2015-08-01 07:42:07
【问题描述】:

我正在尝试使用 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 继续发送数据包的好建议,直到我终止程序/或我按下一个键/或计时器终止它?我应该循环命令吗?提前谢谢你。

【问题讨论】:

    标签: c# ping


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 2020-10-13
      • 1970-01-01
      • 2014-12-03
      • 2015-11-22
      相关资源
      最近更新 更多