【问题标题】:C# Continuous PingC# 连续 Ping
【发布时间】:2020-06-25 20:59:56
【问题描述】:

我正在尝试构建一个真正用于我们的 LAN 进行故障排除的连续 ping 程序。但是,我在实施时遇到了一点困难。

代码实际上正确地解决了问题。 True 开始持续支付,但 false 不会停止。它继续无限循环。我尝试了一些其他循环的配置,但没有成功。

我并没有真正看出我做错了什么,我希望能得到一些帮助。

非常感谢一些帮助。

提前谢谢你。

using System.Threading;

    private void btnContinuousPing_Click(object sender, EventArgs e)
    {
        Task StillLost = Task.Factory.StartNew(() =>
        {
            bool boCheckbox = cbContinuousPing.Checked;
            while (boCheckbox == true)
            {
                PingStuff();
                Thread.Sleep(500);
                if (boCheckbox == false) // Redundant
                {
                    break;
                }
            }
        });
    }

    void PingStuff()
    {
        // Trying to build continuous ping.
        // ISSUE: While loop infinitely.
        // Setting the "cbContinuousPing.Checked" to false
        // doesn't stop the loop.
        Ping pingSender = new Ping();
        PingOptions options = new PingOptions();
        // Fragmentation behavior.
        options.DontFragment = true;
        // Set TTL to 48.
        options.Ttl = 48;
        // Create Empty buffer.
        byte[] buffer = new byte[32];
        // Wait x seconds for a reply.
        int timeout = 4000;
        // Ping device.
        PingReply reply = pingSender.Send("192.168.1.1", timeout, buffer, options);
        // Display Results.
        Invoke(new Action(() =>
        {
            txtContinuousPing.AppendText(string.Format("Address: {0}, byte={1}, time={2}, TTL={3}, Don't fragment: {4}", 
            reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime, options.Ttl, options.DontFragment) + Environment.NewLine);
        }));
    }

【问题讨论】:

    标签: c# ping


    【解决方案1】:

    问题是您在 while 循环之外缓存了一次 boCheckbox 的值,然后在循环内部代码不断检查该值但从不更新它。

    相反,您可以考虑为while 条件使用实际值(而不是缓存值)。此外,您也不需要循环内的冗余检查:

    private void btnContinuousPing_Click(object sender, EventArgs e)
    {
        Task StillLost = Task.Factory.StartNew(() =>
        {
            while (cbContinuousPing.Checked)
            {
                PingStuff();
                Thread.Sleep(500);
            }
        });
    }
    

    【讨论】:

      【解决方案2】:

      把这一行:

      bool boCheckbox = cbContinuousPing.Checked;
      

      在你的 while 循环中。

      【讨论】:

      • 非常感谢菲尔的帮助。你知道,这有点好笑。在我发布之后,我注意到布尔不在循环中。 :-) 一旦我把它放在 while 语句中,它就开始工作了。
      猜你喜欢
      • 2013-01-24
      • 2020-12-08
      • 2016-07-11
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多