繁体   English   中英

c#中的计时器问题

[英]Problem with timers in c#

我已经编写了一个应用程序并使用了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();

    }

您需要在Tick方法中放置timer.Start调用。 例如

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

听起来你不需要六个计时器 - 你需要一个计时器,根据当前状态,它会在触发时执行六个动作中的一个。 我认为这会导致比启动多个计时器更简单的代码。

这里要考虑的第一件事是,如果所有6个定时器都具有完全相同的代码,我肯定你最好只使用一个定时器,而是保持一个状态让你知道你是否处于模式1,2,这也将消除停止第一个计时器和启动新计时器的需要。

所以有一个名为State的类变量,从1开始。当应用程序发生某些事情时,将状态设置为2,让原始计时器继续运行。

拥有6个相同的代码块几乎可以保证,在您更改代码的某个时候,您将在这6个重复项中至少有1个出错。

为什么不改变一个计时器的处理程序并根据需要启动/停止它,而不是创建6个计时器? 它并不表示您的计时器完全并行运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM