沒有做循環,我的代碼運行良好。只要我將它放在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'字段中。 –