The timer and computation should works in a function or an event handler. When you say, it does not works, is it that the text is not updated?
You have to remember that timer and screen refreshing are both low priority. Thus if you make a tight loop and the CPU is in use, nothing will be refreshed during that time.
If you want to update the screen while doing an intensive algorithm, you should look to uses a BackgroundWorker and update the UI every now and then (say every 1/10 of a second).
I don't see any other reason why it would not works (other than the UI thread being busy 100% of the time). But provided code does not give us the full context.
Now for your code:
1)
reset
is set to
true
before being tested.
2) Why not initialize currentTime at the declaration:
DateTime currentTime = DateTime.Now
Or even use DateTime.Now in the expression since the value is not reused elsewhere.
lblElapsed.Text = HMS(DateTime.Now - startTime - stoppedTime);
3) The previous code is incorrect when the timer is in stopped state. Well, I guess that
tmDisplay
would be disabled in that case... but then would the label be updated when the timer is stopped. If so, then the code in
tmDisplay_Tick
should call a function
UpdateElapsedTime()
to avoid code duplication.
private void tmDisplay_Tick(object sender, EventArgs e)
{
UpdateElapsedTime();
}
private void UpdateElapsedTime()
{
lblElapsed.Text = HMS(DateTime.Now - startTime - stoppedTime);
}
That way,
UpdatedElapsedTime()
can be called the the timer is stopped.
4)
HMS
function does not properly work when elapsed time fall exactly on a whole second since
TimeSpan.ToString()
won't display the 0 in that case.
5) Once the previous code fixed, someone would typically use
HMS
function at reset time to ensure that proper formating is used even if
HMS
function is modified.
lblElapsed.Text = HMS(nw TimeSpan());
Even now, it look like an extra decimal was displayed initially...
6) I think that your
HMS
function would keep the final dot and thus it should probably be
s.Length - 7
. But you code would be better if you would remove everything from the last decimal separator (included). Windows provide that information.
If you are using .NET 4.0, then you can use new formatting options:
TimeSpan.ToString()[
^]
Custom TimeSpan Format String[
^]