-1

I am making a countdown clock using dispatchertimer and timespan in WPF. I have a button to start the countdown and a button to stop the countdown. When I hit the start button again it has doubled the interval from one second to two seconds. I display the counting in a textbox. What is wrong? The code is simple:

public partial class MainWindow : Window
{    
   private DispatcherTimer DPtimerA;
  
   private TimeSpan timeA;
   
    
    public MainWindow()
    {
        InitializeComponent();
                 
        DPtimerA = new DispatcherTimer();
        DPtimerA.Interval = new TimeSpan(0, 0, 1);
         
        timeA = TimeSpan.FromSeconds(21);
     
    }

    
    private void DPtimerA_Tick(object sender, EventArgs e)
    {
       
        timeA = timeA.Add(TimeSpan.FromSeconds(-1));
        
        txtClockA.Text = timeA.ToString("c");
        if (timeA == TimeSpan.Zero) DPtimerA.Stop();

    }

      
    private void btnStartA_Click(object sender, RoutedEventArgs e)
    {
        DPtimerA.Tick += DPtimerA_Tick;
        DPtimerA.Start();
       
      
    }

    private void btnStopA_Click(object sender, RoutedEventArgs e)
    {
        DPtimerA.Stop();
    }
}

}

  • 1
    You don't have to subscribe to `Tick` event every time in start button click. You can do that once in constructor itself. – Mat J May 09 '22 at 16:22

2 Answers2

0

Change it like this:

  private void btnStartA_Click(object sender, RoutedEventArgs e)
  {
      DPtimerA.Tick -= DPtimerA_Tick;
      DPtimerA.Tick += DPtimerA_Tick;
      DPtimerA.Start();
  }
Ohad Cohen
  • 597
  • 4
  • 9
0

Make DispatcherTimer a readonly field that you initialize and hook up an event handler to once:

public partial class MainWindow : Window
{
    private readonly DispatcherTimer DPtimerA = 
        new DispatcherTimer() { Interval = new TimeSpan(0, 0, 1) };
    private TimeSpan timeA = TimeSpan.FromSeconds(21);

    public MainWindow()
    {
        InitializeComponent();
        DPtimerA.Tick += DPtimerA_Tick;
    }


    private void DPtimerA_Tick(object sender, EventArgs e)
    {
        timeA = timeA.Add(TimeSpan.FromSeconds(-1));

        txtClockA.Text = timeA.ToString("c");
        if (timeA == TimeSpan.Zero)
            DPtimerA.Stop();
    }


    private void btnStartA_Click(object sender, RoutedEventArgs e)
    {
        DPtimerA.Start();
    }

    private void btnStopA_Click(object sender, RoutedEventArgs e)
    {
        DPtimerA.Stop();
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88