【问题标题】:Why doesn't Ping.Send work in a for-loop?为什么 Ping.Send 不在 for 循环中工作?
【发布时间】:2017-08-16 00:26:08
【问题描述】:

for 循环中的内容本身可以正常工作,但当前循环运行后,PingTimes 列表始终为空。这里发生了什么?在这里对 C# 很陌生。

        private void PingTest()
    {
        List<long> PingTimes = new List<long>();
        Ping PingSender = new Ping();
        PingOptions options = new PingOptions();

        options.DontFragment = true;

        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 120;


        for (int i = 1; i >= TimesToPing; i++)
        { 
            PingReply reply = PingSender.Send(PingAddress, timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                PingTimes.Add(reply.RoundtripTime);
            }
            else
            {
                MessageBox.Show("Ping test failed due to an unknown reason.");
                break;
            }
        }
        MessageBox.Show("Pinged Address: " + PingAddress + "\nAverage Ping: " + PingTimes.Average().ToString() + "ms");
    }

【问题讨论】:

  • 计算机科学硕士应该真的知道如何使用调试器

标签: c# .net for-loop asynchronous ping


【解决方案1】:

您的 for 循环条件被反转,因此循环将永远不会运行。 :)

【讨论】:

  • 这太丢人了。
  • @Ricochet 只是一个提示,我并不是说这是一个老二,但是当循环不正常时,在循环内放置一个打印以确保循环本身运行为你期待。
猜你喜欢
  • 2019-07-03
  • 1970-01-01
  • 2014-10-15
  • 2020-09-06
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多