I'm trying to trigger the Stopwatch.reset();
if the elapsed time is equal to the time value stored in a DateTime object workDt
by using the .equals() to compare the elapsed time of the stopwatch with the time of day stored in my DateTime
object workDt.
Basically the onTapped event triggers my Stopwatch to start and updates a textblock with the current elapsed time.
I've then passed a user inputted time value "00 : 00 : 07 : 000"
to a DateTime object which I'm aiming to use for the comparison. The problem is I the condition is never met to trigger myStopwatch.reset();
In testing I set the string as follows which I then set a break point on the workDt and it shows the correct time is being stored but it doesn't trigger the condition.
private async void startBtn_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
//delay stop watch start to allow time to get ready.
TimeSpan time = TimeSpan.FromSeconds(1);
await System.Threading.Tasks.Task.Delay(time);
string wrkString;
string rstString;
int i;
//set text box editing to false to prevent illegal input.
wrkTbx.IsEnabled = false;
restTbx.IsEnabled = false;
roundSlider.IsEnabled = false;
roundsTbx.IsEnabled = false;
//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);
//Run the timer for until i reaches the number of rounds value.Eg, 4 rounds
//for (i = 0; i <= roundSlider.Value; i++ )
//{
StopGoCvs.Background = new SolidColorBrush(Colors.Green);
//startSoundElmt.Play();
// set up the timer
myTimer = new DispatcherTimer();
myTimer.Interval = new TimeSpan(0, 0, 0, 0, 1);
myTimer.Tick += myTimer_Tick;
// start both timers
myTimer.Start();
myStopwatch.Start();
//reset timer if date time value is equal to current elapsed time.
if(myStopwatch.Elapsed.Equals(workDt.TimeOfDay))
{
myStopwatch.Reset();
}
}
Is this the correct way to achieve this or should I be using a different method?
The chances of the elapsed time being exactly the same as the required time - down to the tick - are tiny.
Instead, you should see whether at least the right amount of time has passed:
if (myStopwatch.Elapsed >= workDt.TimeOfDay)
However, the place that you're checking that is inappropriate - you're checking just after starting the timer. Shouldn't you be checking it in the timer tick event?
See more on this question at Stackoverflow