如何在不同的时间间隔内使用相同的计时器?

ghd*_*ghd 4 c# winforms

我在我的代码中使用了一个计时器.状态栏在点击事件中更新,点击属性中提到的时间间隔的相应按钮,例如一秒钟.现在我想在不同的时间间隔内使用相同的计时器,例如两秒钟进行不同的操作.怎么实现呢?

Mit*_*eat 6

创建第二个计时器.黑客攻击第一个计时器没有任何好处.

正如@Henk所说,计时器并不昂贵.(特别是没有比较难以维护代码!)


dec*_*one 2

我同意@Henk 和其他人的观点。

但是,像这样的事情仍然可以工作:

例子

    Int32 counter = 0;

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (counter % 1 == 0)
        {
            OnOneSecond();
        }

        if (counter % 2 == 0)
        {
            OnTwoSecond();
        })

        counter++;
    }
Run Code Online (Sandbox Code Playgroud)

更新的示例

private void Form_Load()
{
    timer1.Interval = 1000; // 1 second
    timer1.Start(); // This will raise Tick event after 1 second
    OnTick(); // So, call Tick event explicitly when we start timer
}

Int32 counter = 0;

private void timer1_Tick(object sender, EventArgs e)
{
    OnTick();
}

private void OnTick()
{
    if (counter % 1 == 0)
    {
        OnOneSecond();
    }

    if (counter % 2 == 0)
    {
        OnTwoSecond();
    }

    counter++;
}
Run Code Online (Sandbox Code Playgroud)

  • 但是,正如您所知,这不是一个好的做法。这只是为了满足你的好奇心。 (3认同)