【发布时间】:2015-10-20 12:59:26
【问题描述】:
没有 do 循环,我的代码运行良好。一旦我将它放在 do 或 while 循环中,代码就无法更新颜色状态。任何的想法?根据我从互联网上收集的信息,我的循环编写正确。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Threading;
namespace SystemsUpDown
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
bool ContinuePing = false;
private void QuitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void StartButton_Click_1(object sender, EventArgs e)
{
Ping ping = new Ping();
ContinuePing = true;
do
{
try ///ping google
{
PingReply reply = ping.Send("8.8.8.8");
if (reply.Status == IPStatus.Success)
{
GoogleStatusLabel.BackColor = Color.Green;
}
}
catch
{
GoogleStatusLabel.BackColor = Color.Red;
}
try ///ping Yahoo!
{
PingReply reply = ping.Send("www.yahoo.com");
if (reply.Status == IPStatus.Success)
{
YahooStatusLabel.BackColor = Color.Green;
}
}
catch
{
YahooStatusLabel.BackColor = Color.Red;
}
try ///ping Reddit.com
{
PingReply reply = ping.Send("www.reddit.com");
if (reply.Status == IPStatus.Success)
{
RedditStatusLabel.BackColor = Color.Green;
}
}
catch
{
RedditStatusLabel.BackColor = Color.Red;
}
try ///ping Chive
{
PingReply reply = ping.Send("www.chive.com");
if (reply.Status == IPStatus.Success)
{
ChiveStatusLabel.BackColor = Color.Green;
}
}
catch
{
ChiveStatusLabel.BackColor = Color.Red;
}
try ///ping CNN
{
PingReply reply = ping.Send("www.cnn.com");
if (reply.Status == IPStatus.Success)
{
CNNStatusLabel.BackColor = Color.Green;
}
}
catch
{
CNNStatusLabel.BackColor = Color.Red;
}
} while (ContinuePing);
}
private void StopButton_Click(object sender, EventArgs e)
{
GoogleStatusLabel.BackColor = Color.Yellow;
ChiveStatusLabel.BackColor = Color.Yellow;
CNNStatusLabel.BackColor = Color.Yellow;
RedditStatusLabel.BackColor = Color.Yellow;
YahooStatusLabel.BackColor = Color.Yellow;
ContinuePing = false;
}
}
}
【问题讨论】:
-
因为你没有给 UI 任何时间来更新,而不是使用 do..loop,使用
System.Windows.Forms.Timer并定期运行它。 -
同意。线程将永远忙于
StartButton_Click_1,因此即使另一个事件已触发并且StopButton_Click处于“队列中”,它也永远不会运行,因为另一个方法永远不会完成。修复后,请考虑将字段ContinuePing设置为volatile字段。