我编写了一个应用程序并使用了 6 个必须依次启动的计时器,但这些计时器无法正常工作。我对定时器了解不多。
例如,timer1 启动,应用程序发生了一些事情。然后 timer1 必须永远停止并且 timer2 必须立即启动并且应用程序中会发生一些事情。然后 timer2 必须永远停止,timer3 必须启动等等。
请帮忙。
这是我的代码:
int yyyy = 0;
void move()
{
yyyy++;
if (yyyy <= 1)
{
timer1.Start();
timer1.Interval = 15;
timer1.Tick += new EventHandler(timer_Tick1);
}
if (yyyy <= 2)
{
timer2.Start();
timer2.Interval = 15;
timer2.Tick += new EventHandler(timer_Tick2);
}
if (yyyy <= 3)
{
timer3.Start();
timer3.Interval = 15;
timer3.Tick += new EventHandler(timer_Tick3);
}
if (yyyy <= 4)
{
timer4.Start();
timer4.Interval = 15;
timer4.Tick += new EventHandler(timer_Tick4);
}
if (yyyy <= 5)
{
timer5.Start();
timer5.Interval = 15;
timer5.Tick += new EventHandler(timer_Tick5);
}
if (yyyy <= 6)
{
timer6.Start();
timer6.Interval = 15;
timer6.Tick += new EventHandler(timer_Tick6);
}
}
和:(例如 timer2)。
(所有计时器都具有完全相同的以下代码)。
int t = 0;
private void timer_Tick2(object sender, EventArgs e)
{
t++;
if (t <= 150)
{
// do somthing
}
else
timer2.Stop();
}
最佳答案
您需要将 timer.Start
调用放在 Tick
方法中。例如
private void timer1_Tick(object sender, EventArgs e)
{
// Make sure you stop the timer first
timer1.Stop();
// Do something
timer1.Enabled = false;
timer2.Enabled = true;
timer2.Start();
}
但这当然不是前进的方式。实现单个 Timer
并使用一个应用程序状态,您可以检查该状态以确定接下来应调用哪个方法。这将降低复杂性并使您的代码更简单。例如
private void timer1_Tick(object sender, EventArgs e)
{
// Stop the timer
timer1.Stop();
// Select which method should be called
switch (whatDoINeedToRun)
{
case "RunMeSecond":
// Do something
break;
case "RunMeThird":
// Do something
break;
case "RunMeFourth":
// Do something
break;
// etc.
default:
// This is the first method call
break;
}
// Restart the timer
timer1.Start();
}
关于c# - c#中定时器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4896446/