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();
}
}
使计时器对象成为全局对象,以便类中的所有方法或事件都可以访问,然后启动计时器给每次到达的时间都分配一个事件,然后在该事件上有条件地检查时间是否达到您的预期时间,然后停止计时器。
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.