-1

I want to run timer countdown (DispatchTimer) multiple times in a loop, one after another. I want to wait until one timer stops and then run another one.

I'm gonna try something like this:

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

My problem is that method RunInterval or RunTimer doesn't wait until timer will stop.

What can I do about it?

arrchi
  • 3
  • 3
  • You're better off starting the timer just once. In the event `Timer1OnTick` can you not just track how many times it has been hit then unhook once the target is achieved? – William Nov 26 '15 at 18:45
  • @HenkHolterman the loop finishes so fast so it would not be noticeable. – M.kazem Akhgary Nov 26 '15 at 18:53
  • @HenkHolterman are you sure? the `RunTimer` method just sets up one DispatcherTimer. i think it will done in very short time. – M.kazem Akhgary Nov 26 '15 at 18:57

1 Answers1

0

Maybe something like this?

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

Instead of looping to create the timers just keep track in the event how many times it's been hit and then unhook the event once that target has been achieved.

William
  • 1,837
  • 2
  • 22
  • 36