Home > Blockchain >  WPF Dispatchertimer tick increments,
WPF Dispatchertimer tick increments,

Time:05-11

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

}

CodePudding user response:

Change it like this:

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

CodePudding user response:

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