2014-10-03 93 views
1

我已经将一个字符串值从一个文本框中分配给一个日期时间变量。它的目的是作为一个标志来告诉myTimer对象在达到存储在workDt中的时间时停止(日期时间变量) 。如何在设定的时间间隔后停止Timer对象?

我试过的当前实现如下,我设置了一个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(); 

      } 



     } 

回答

1

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

myTimer.Interval == workDt.TimeOfDay 

以往任何时候都得到满足

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

+0

看来我应该使用检查存储在myStopwatch经过时间的值而不是定时器对象的解释。你有什么建议如何检查?我试过'if(myStopwatch.Elapsed = workDt.TimeOfDay)',但它不是一个有效的赋值。 – 2014-10-07 18:29:55

1

让计时器对象全球化,所以,在一个类中的所有方法或事件可以访问,然后开始计时每次都达到给一个事件,然后在该事件有条件检查的时间范围为您的预计时间是否然后停止定时器。

相关问题