Tyler
Tyler

Reputation: 882

C# timer_Tick() countdown counts down in 2 steps

I'm trying to program a program which opens a form on a button click. This form has a label with a countdown in it. The main form has a button which does the following:

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();
    }
}

Then it opens the second form. The code for my countdown is the following:

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;
            }
        }
    }
}

The problem is: The countdown counts down in 2 steps (e.g. 20 - 18 - 16 etc. instead of 20 - 19 - 18 - 17 etc.). In debugging mode it counts correct.

Any suggestions?

Upvotes: 1

Views: 87

Answers (1)

daryal
daryal

Reputation: 14919

The code section below the following line smells:

foreach (string ipAddress in ipAddressCollection)

You are simply decrementing the timeLeft for each ipAddress. So if you have 45 strings in ipAddressCollection timeLeft will be zero even in the first tick.

Upvotes: 4

Related Questions