How to stop a Timer object after a set interval of

2019-08-12 03:56发布

问题:

I've assigned a string value from a text box to a date time variable.It's purpose is to serve as a flag to tell myTimer object to stop when it has reached the the time stored in workDt,(the date time variable).

The current implementation I have tried is the following, where I set up an if..else statement to check if the timer's current time is equal to what was entered in the text box but it doesn't trigger the timer to stop.

I set a break point on the 'if' statement and the time value is being stored in the workDt but isn't triggering the timer to stop.

Can anyone see a flaw in my implementation or offer any advice on an alternative solution?

private void startBtn_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {


            string wrkString;
            string rstString; 


            //Assign text box time string to string variables.
            wrkString = wrkTbx.Text;
            rstString = restTbx.Text;


            //Assign text box string value to a date time variable.

            DateTime workDt = DateTime.ParseExact(wrkString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);
            DateTime restDt = DateTime.ParseExact(rstString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);


            StopGoCvs.Background = new SolidColorBrush(Colors.Green);
            hornElmt.Play();
            //    // set up the timer
            myTimer = new DispatcherTimer();
            myTimer.Interval = new TimeSpan(0, 0, 0, 0, 1);
            myTimer.Tick += myTimer_Tick;

            //tell timer to stop when it has reached the allocated work time.
            if(myTimer.Interval != workDt.TimeOfDay)
            {
                // start both timers
                myTimer.Start();
                myStopwatch.Start();

            }
            else
            {
                myTimer.Stop();
                myStopwatch.Stop();

            }



        }

回答1:

setting the Interval to: myTimer.Interval = new TimeSpan(0, 0, 0, 0, 1); means you set a 1ms Interval thus making in it impossible for the condition:

myTimer.Interval == workDt.TimeOfDay

ever to be met

What you are looking for is more of a StopWatch rather than a timer.



回答2:

Make timer object global so that all method or events in a class can access that then start timer give an event to every time reach and then on that event conditionally check whether the time reach as your expected time then stop the timer.