0

通过以下代码(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();
}

我们不能在 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
}

无论我是否取消注释该行Thread.Sleep(60000);,我们都看到 in 没有任何lblTimer_Value_InBuildings变化timer2_Tick

你能给我一个解决方案(带或不带计时器)吗?

4

3 回答 3

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;

   }
}
于 2013-02-02T00:16:02.650 回答
2

当您执行 Thread.Sleep(60000) 时,您是在告诉 UI 线程休眠 60 秒。这也会阻止定时器的执行,因为 UI 线程挂起休眠而不是处理诸如定时器休眠之类的事件。

于 2013-02-01T23:54:35.397 回答
1

代码完全让我感到无聊

方法:

private void timer1_Tick(object sender, EventArgs e) {
    timer2.Enabled=false;
    timer1.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();
}

private void timer3_Tick(object sender, EventArgs e) {
    if(0!=(int)timer3.Tag) {
        // your code goes here and peformed per step
        timer1.Enabled=true;
        timer2.Enabled=true;
    }

    timer3.Tag=(1+(int)timer3.Tag)%Max_Step;
}

缩写:

var delayedInterval=60000;

timer1.Interval=60000;
timer2.Interval=1000;
timer3.Interval=delayedInterval+timer1.Interval;

lblTimer_Value_InBuildings.Text="0";
timer3.Tag=1;
timer3.Enabled=true;

您的原始代码永远不会生成timer1timer2停止,所以我认为您应该更正timer7andtimer8timer1and timer2,否则它们在这里没有意义。

于 2013-02-02T05:37:51.013 回答