2014-06-13 150 views
1

我試圖編寫一個程序,它打開一個按鈕單擊窗體。此表單中有倒數的標籤。主窗體有一個按鈕,它執行以下操作:C#timer_Tick()倒計時2步倒計時

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

的問題是:倒計時在2個步驟進行倒計時(例如20 - 18 - 16等來代替20 - 19 - 18 - 17等)。在調試模式下,它計數正確。

有什麼建議嗎?

+0

如果您在每次打勾後刷新標籤,該怎麼辦? 'infoLabel.Refresh();' – Montaldo

+1

可能在「發佈」中你有2個連接,所以它從timeLeft中減去兩次。也許你應該把'timeLeft = timeLeft - 1'移到'for'語句之外。 – dburner

+0

foreach正在運行兩次。通過調試來檢查它。 – Ricky

回答

4

以下行下面的代碼段氣味:

foreach (string ipAddress in ipAddressCollection) 

你只是遞減timeLeft每個ipAddress。因此,如果您在ipAddressCollection時間內有45個字符串,則即使在第一次打勾時,timeLeft也將爲零。