繁体   English   中英

C# 连续 Ping

[英]C# Continuous Ping

我正在尝试构建一个真正用于我们 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);
        }));
    }

把这一行:

bool boCheckbox = cbContinuousPing.Checked;

在你的 while 循环中。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM