繁体   English   中英

在设置的时间间隔后如何停止Timer对象?

[英]How to stop a Timer object after a set interval of time?

我已经从文本框中为日期时间变量分配了一个字符串值。它的目的是用作一个标志,告诉myTimer对象在到达workDt(日期时间变量)中存储的时间时停止。

我尝试过的当前实现如下所示,其中设置了if..else语句来检查计时器的当前时间是否等于在文本框中输入的时间,但不会触发计时器停止。

我在'if'语句上设置了一个断点,并且时间值存储在workDt中,但没有触发计时器停止。

谁能看到我的实现中的缺陷或就替代解决方案提供任何建议?

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

            }



        }

使计时器对象成为全局对象,以便类中的所有方法或事件都可以访问,然后启动计时器给每次到达的时间都分配一个事件,然后在该事件上有条件地检查时间是否达到您的预期时间,然后停止计时器。

将时间间隔设置为: myTimer.Interval = new TimeSpan(0, 0, 0, 0, 1); 表示您将时间间隔设置为1ms,因此无法满足以下条件:

myTimer.Interval == workDt.TimeOfDay

永远被满足

您正在寻找的更多是秒表而不是计时器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM