C#timer_Tick()倒计时分为两步倒计时

时间:2014-06-13 08:19:19

标签: c#

我试图编写一个程序,在按钮点击时打开一个表单。此表单中有一个带倒计时的标签。主窗体有一个按钮,可执行以下操作:

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等)。在调试模式下,它是正确的。

有什么建议吗?

1 个答案:

答案 0 :(得分:4)

以下行下面的代码部分有气味:

foreach (string ipAddress in ipAddressCollection)

您只是为每个timeLeft递减ipAddress。因此,如果ipAddressCollection中有45个字符串,则即使在第一个刻度线中,时间也将为零。