-->

C# Stopwatch on-the-fly update

2019-03-01 05:09发布

问题:

(My first question here!) Hi, I am kind of beginner in c#. I tried to build a simple timer (in Windows.Forms). I made a label which indicates the time, and used the StopWatch class (from system.diagnostics). The trigger event for starting / stopping the stopwatch is the spacebar KeyDown event. After the second tap the stopwatch stops and Label.text is assigned to the Stopwatch.Elapsed value. I want to continuously update the label, but I don't know how. If I make while(StopWatchName.IsRunning) in the event itself, the event will indefinitely continue and won't respond for the second tap.

Thanks in advance for any ideas!

回答1:

You should probably have a timer which fires frequently (e.g. every 10ms) - start the timer when you start the stopwatch, and stop the timer when you stop the stopwatch. The timer tick event would just set the label's Text property from the stopwatch.

The timer's interval won't be exact of course - but that's okay, because the point is to rely on the stopwatch for the actual timing. The timer is just there to update the label frequently.



回答2:

You are probably going to want to use System.Timers. Timer class in order to call a function every few seconds to update your UI with the time elapased value.

Here is a good Sample: http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

Basically, your OnTimedEvent event function from the sample is what will accomplish thisin your code.

EDIT: John is correct (see comments) you should be using Forms.Timer you can avoid thread marshaling. http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

TimerEventProcessor would be the function of concern in that sample.