c#如何在循环中运行多个计时器。一个接一个的计时器

时间:2015-11-26 18:37:02

标签: c# timer countdown dispatchertimer

我想在一个循环中一个接一个地多次运行计时器倒计时(DispatchTimer)。我想等到一个计时器停止然后运行另一个计时器。

我会尝试这样的事情:

public TimeSpan CurrentTimeSpan;
private void RunInterval()
{
    for (int i = 0; i < 10; i++)
    {
        RunTimer(new TimeSpan(0, 0, 0, 30));        

    }
}
private void RunTimer(TimeSpan Timer)
{
    DispatcherTimer timer1 = new DispatcherTimer();
    timer1.Interval = new TimeSpan(0, 0, 0, 1);
    CurrentTimeSpan = Timer;
    timer1.Tick += Timer1OnTick;

}
private void Timer1OnTick(object sender, object o)
{
    DispatcherTimer timer = (DispatcherTimer) sender;
    CurrentTimeSpan = CurrentTimeSpan.Subtract(timer.Interval);
    if (CurrentTimeSpan.TotalSeconds == 0)
    {
        timer.Stop();
    }
}

我的问题是方法RunInterval或RunTimer不会等到计时器停止。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

也许是这样的?

   private int hitCount = 0;
   public TimeSpan CurrentTimeSpan;  

    private void RunInterval()
    {
        RunTimer(new TimeSpan(0, 0, 0, 30));
    }
    private void RunTimer(TimeSpan Timer)
    {
        DispatcherTimer timer1 = new DispatcherTimer();
        timer1.Interval = new TimeSpan(0, 0, 0, 1);
        CurrentTimeSpan = Timer;
        timer1.Tick += Timer1OnTick;

    }
    private void Timer1OnTick(object sender, object o)
    {
        DispatcherTimer timer = (DispatcherTimer)sender;

        if(hitCount == 10)
        {
             timer.Tick -= Timer1OnTick
        }

        CurrentTimeSpan = CurrentTimeSpan.Subtract(timer.Interval);
        if (CurrentTimeSpan.TotalSeconds == 0)
        {
            timer.Stop();
        }
    }

不是循环创建计时器,只需跟踪事件被击中的次数,然后在达到目标后取消挂钩事件。