Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

added some error checking into DateTimePrecise and droped the default…

… syncSeconds down to 1 second
  • Loading branch information...
commit 05472806aedced54f0dd76055ee82c672fc4067f 1 parent e146ad6
@nberardi nberardi authored
Showing with 20 additions and 3 deletions.
  1. +20 −3 src/System/DateTimePrecise.cs
View
23 src/System/DateTimePrecise.cs
@@ -6,7 +6,7 @@ namespace System
{
public class DateTimePrecise
{
- private static readonly DateTimePrecise Instance = new DateTimePrecise(10);
+ private static readonly DateTimePrecise Instance = new DateTimePrecise();
public static DateTime Now
{
@@ -30,13 +30,16 @@ public static DateTimeOffset UtcNowOffset
private const long TicksInOneSecond = 10000000L;
+ private readonly double _divergentSeconds;
private readonly double _syncSeconds;
private readonly Stopwatch _stopwatch;
private DateTimeOffset _baseTime;
- public DateTimePrecise(int syncSeconds)
+ public DateTimePrecise(int syncSeconds = 1, int divergentSeconds = 1)
{
_syncSeconds = syncSeconds;
+ _divergentSeconds = divergentSeconds;
+
_stopwatch = new Stopwatch();
Syncronize();
@@ -52,6 +55,7 @@ private void Syncronize()
public DateTimeOffset GetUtcNow()
{
+ var now = DateTimeOffset.UtcNow;
var elapsed = _stopwatch.Elapsed;
if (elapsed.TotalSeconds > _syncSeconds)
@@ -62,8 +66,21 @@ public DateTimeOffset GetUtcNow()
elapsed = _stopwatch.Elapsed;
}
+ /**
+ * The Stopwatch has many bugs associated with it, so when we are in doubt of the results
+ * we are going to default to DateTimeOffset.UtcNow
+ * http://stackoverflow.com/questions/1008345
+ **/
+
+ // check for elapsed being less than zero
if (elapsed < TimeSpan.Zero)
- elapsed = TimeSpan.Zero;
+ return now;
+
+ var preciseNow = _baseTime + elapsed;
+
+ // make sure the two clocks don't diverge by more than defined seconds
+ if (Math.Abs((preciseNow - now).TotalSeconds) > _divergentSeconds)
+ return now;
return _baseTime + elapsed;
}
Please sign in to comment.
Something went wrong with that request. Please try again.