【发布时间】: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);
}));
}
【问题讨论】: