tags:

views:

54

answers:

3

Hi,

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 computer 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.

A: 

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
AnthonyWJones
This is possible but since the Dispatcher works with a priority queue it is not guaranteed that the computed duration will be accurate and there will be a growing lag over time
Gilad
@Gilad: I guess it depends on what your resolution is? Minutes? Seconds? Milliseconds? also on whether an event may be skipped or if all events are queued. You'd want to make the interval significantly less than your desired resolution. You might also combine this approach with comparing dates, this approach allows you to detect a significant mismatch between interval and DateTime difference thus indicating the system time as been modified.
AnthonyWJones
A: 

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.

Henrik Söderlund
A: 

If you don't need precision fetch from a time server?

PeanutPower