I need to calculate how much time has passed from one state to another in Silverlight 3.0.
it is most common to do:
DateTime Start = DateTime.UtcNow;
.
.
.
DateTime End = DateTime.UtcNow;
TimeSpan Duration = End - Start;
BUT, this doesn't cover a case were the user changed the computer time. Is there a way to get the same effect using some other timer? For instance, a timer that counts the time since the compute开发者_运维问答r was turned on (Easy in C# but blocked in SL) or any other timer that isn't based on DateTime.Now or DateTime.UtcNow.
Gilad.
You could us the DispatcherTimer
with an interval set at the required resolution:-
Private WithEvents timer as DispatchTimer = New DispatcherTimer()
Private counter As Integer = 0
Private Sub TimerClick(ByVal sender as System.Object, ByVal e As EventArgs) Handles timer.Tick
counter += 1
End Sub
Private Sub StartTiming()
counter = 0
timer,Interval = TimeSpan.FromSeconds(1)
timer.Start()
End Sub
Private Function EndTiming() as TimeSpan
timer.Stop()
Return TimeSpan.FromSeconds(counter)
End Function
You could try to detect changes to the computer time by using a dispatchertimer that saves DateTime.Now to a variable on each tick. Then on the next tick you check whether the current time is equal to the saved value + whatever interval your timer is running at. And then, if it is not, I guess you could pop up some alert saying "No cheating" or whatever and abort your app. This way you could still use the "correct" way of calculating a time span and still prevent users from changing the computer time. I suppose you would have to take into account the previously mentioned lag that might occur in the timer and somehow adjust for it. You dont want that alert to popup unless a significant change occured in the computer time.
If you don't need precision fetch from a time server?
You need to retrieve a timestamp that is not associated with absolute time. System.Diagnostics.Stopwatch
can achieve this, and it also has much higher resolution.
精彩评论