一段时间后如何停止一个Timer对象? [英] How to stop a Timer object after a set interval of time?

查看:219
本文介绍了一段时间后如何停止一个Timer对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从文本框中指定了一个字符串值到date time变量。它的目的是作为一个标志来告诉myTimer对象在达到存储在workDt中的时间(日期时间变量)

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).

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

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.

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

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

            }



        }


推荐答案

将间隔设置为: myTimer.Interval = new TimeSpan(0,0,0,0,1);
意味着你设置一个1ms间隔,从而使它不可能
的条件:

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

曾经遇到过

你正在寻找的是更多的一个 StopWatch ,而不是一个计时器。

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

这篇关于一段时间后如何停止一个Timer对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆