【问题标题】:How to stop a Timer object after a set interval of time?如何在设定的时间间隔后停止 Timer 对象?
【发布时间】:2014-11-28 10:37:10
【问题描述】:

我已经将文本框中的字符串值分配给日期时间变量。它的目的是作为一个标志来告诉 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();

            }



        }

【问题讨论】:

    标签: c# datetime windows-phone-8 timer stopwatch


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      将间隔设置为:myTimer.Interval = new TimeSpan(0, 0, 0, 0, 1); 意味着您设置了 1ms 的间隔,因此不可能 条件:

      myTimer.Interval == workDt.TimeOfDay
      

      永远遇见

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

      【讨论】:

      • 看来我应该使用检查存储在 myStopwatch 中的值,而不是解释的计时器对象。你对如何检查有什么建议吗?我试过if(myStopwatch.Elapsed = workDt.TimeOfDay),但这不是一个有效的分配。
      猜你喜欢
      • 2012-07-31
      • 1970-01-01
      • 2013-10-31
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2011-02-25
      相关资源
      最近更新 更多