我正在尝试编写一个程序,在单击按钮时打开一个表单。此表单有一个带有倒计时的标签。主窗体有一个按钮,它执行以下操作:
private void btnOpen_Click(object sender, EventArgs e)
{
List<string> ips = new List<string>();
if (pcTreeView.SelectedNodes.Count > 1)
{
foreach (RadTreeNode node in machinesTreeView.SelectedNodes)
{
foreach (XmlNode client in xdoc.SelectNodes("/clients/client"))
{
if (node.Text == client["clientShortName"].InnerText)
{
string ipAddress = client["clientIP"].InnerText;
ips.Add(client["clientIP"].InnerText);
clientNodeList.Add(node);
}
}
}
MsgBox msgbox = new MsgBox();
msgbox.ipAddressCollection = ips;
msgbox.Tag = "test";
msgbox.ShowDialog();
}
}
然后它打开第二个表单。我的倒计时代码如下:
int timeLeft = 45;
public List<string> ipAddressCollection { get; set; }
private void MsgBox_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private async void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
foreach (string ipAddress in ipAddressCollection)
{
if (this.Tag.ToString() == "test")
{
if (rebootShutdownTime > 0)
{
timeLeft = timeLeft - 1;
infoLabel.Text = "Countdown: " + timeLeft.ToString();
timer1.Enabled = true;
}
}
}
}
问题是:倒计时分两步倒计时(例如 20 - 18 - 16 等,而不是 20 - 19 - 18 - 17 等)。在 Debug模式下它是正确的。
有什么建议吗?
请您参考如下方法:
以下行下方的代码部分有异味:
foreach (string ipAddress in ipAddressCollection)
您只是为每个 ipAddress 递减 timeLeft。因此,如果 ipAddressCollection 中有 45 个字符串,即使在第一个滴答中,timeLeft 也将为零。
