如何使用定时器在for循环中添加延迟

Sil*_*ght 0 c# sleep timer windows-applications

通过以下代码(timer2的间隔为1000)

private void timer1_Tick(object sender, EventArgs e) {
    timer7.Enabled=false;
    timer8.Enabled=false;
    lblTimer_Value_InBuildings.Text="0";
}

private void timer2_Tick(object sender, EventArgs e) {
    lblTimer_Value_InBuildings.Text=(int.Parse(lblTimer_Value_InBuildings.Text)+1).ToString();
}
Run Code Online (Sandbox Code Playgroud)

我们不能在for循环中创建延迟

for(int i=1; i<=Max_Step; i++) { 
    // my code... 

    // I want delay here: 
    timer1.Interval=60000; 
    timer1.Enabled=true; 
    timer2.Enabled=true; 

    // Thread.Sleep(60000); // makes no change even if uncommenting
}
Run Code Online (Sandbox Code Playgroud)

我是否取消对该行Thread.Sleep(60000);或不行,我们什么也看不到有改变lblTimer_Value_InBuildingstimer2_Tick.

你能给我一个解决方案(有或没有计时器)?

Joh*_*ner 5

你的计时器是你的循环,你不需要for循环.您只需跟踪函数调用之外的循环变量.我建议将所有这些功能包装到一个类中,以使其与GUI代码分开.

private int loopVar = 0;
public void Form_Load()
{
    // Start 100ms after form load.
    timer1.Interval = 100;
    timer1.Enabled = true;
}


private void timer1_Tick(object sender, EventArgs e)
{
   timer1.Enabled = false;
   //  My Code Here
   loopVar++;

   if (loopVar < Max_Step)
   {
      // Come back to the _tick after 60 seconds.
      timer1.Interval = 60000;
      timer1.Enabled = true;

   }
}
Run Code Online (Sandbox Code Playgroud)