damu_d
damu_d

Reputation: 53

Unable to reset time duration

On this code I am starting and stopping random sampling based on a fixed sampling time. When I clicked stop sampling, timers stops correctly. But when I start back again, the times do not start correctly. could you please help to check what is wrong here?

 public partial class MainWindow : Window
    {
       
        public float samplingTime = 10f;
        double currentDateTime = 0.0;
        DateTime dtEnd;
        public bool running;

        public MainWindow()
        {
            InitializeComponent();

            
            timer1 start.code()

            void timer_Tick(object sender, EventArgs e)
            {
              dtEnd = DateTime.Now.AddSeconds(samplingTime);   
               someCode();
            }
        }

        private void startSample_Click(object sender, RoutedEventArgs e)
        {
           
           timer2 start code()
            void windowtimer_Tick(object sender, EventArgs e)
            {
                currentDateTime = (dtEnd - DateTime.Now).TotalSeconds;
               
                if (currentDateTime < 0.1 && running == true)
                {
                    code();
                }

            }
        }

        private void stopSample_Click(object sender, RoutedEventArgs e)
        {
       
            timer.Stop();
            windowTimer.Stop();
            
        }

Upvotes: -3

Views: 42

Answers (1)

Charlieface
Charlieface

Reputation: 72480

You are adding the Tick handler multiple times:

windowTimer.Tick += windowtimer_Tick;

is executed every time you start, but you don't unhook it. Probably you should set the handler elsewhere (in the designer maybe).

Or you can add:

windowTimer.Tick -= windowtimer_Tick;

to the Stop handle

Upvotes: 1

Related Questions