Created
January 19, 2017 22:37
-
-
Save eriksimonic/669d37d8a3a689a1dc4ef1cdf4e6be47 to your computer and use it in GitHub Desktop.
Time Diff.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var locaTime = DateTime.Now; | |
IServiceSyncedTime ts = new SyncDateTime(new NAVTimeService()); | |
locaTime.Dump(); | |
Thread.Sleep(5000); | |
ts.GetCurrentTime().Dump(); | |
} | |
public interface IServiceSyncedTime | |
{ | |
void UpdateTimeDiff(); | |
DateTime GetCurrentTime(); | |
} | |
public interface ITimeService | |
{ | |
bool GetTime(int timeoutMisliseconds); | |
DateTime ServiceTime {get; } | |
long RequestMiliseconds {get;} | |
} | |
public class NAVTimeService :ITimeService { | |
public bool GetTime(int timeoutMisliseconds) | |
{ | |
Stopwatch st = new Stopwatch(); | |
st.Start(); | |
System.Threading.Thread.Sleep(5000); | |
st.Stop(); | |
if(st.ElapsedMilliseconds > timeoutMisliseconds) return false; | |
RequestMiliseconds = st.ElapsedMilliseconds / 2; | |
ServiceTime = DateTime.Now; | |
return true; | |
} | |
public long RequestMiliseconds { get; private set; } | |
public DateTime ServiceTime {get; private set;} | |
} | |
public class SyncDateTime : IServiceSyncedTime | |
{ | |
public SyncDateTime(ITimeService _timeService) | |
{ | |
this._timeService = _timeService; | |
} | |
private ITimeService _timeService; | |
private TimeSpan _timeDiff = TimeSpan.MinValue; | |
private readonly object _lock = new Object(); | |
public void UpdateTimeDiff() | |
{ | |
if(_timeService.GetTime(1000)) | |
{ | |
lock(_lock) | |
_timeDiff = DateTime.Now - _timeService.ServiceTime.AddMilliseconds(_timeService.RequestMiliseconds); | |
} | |
} | |
public DateTime GetCurrentTime() | |
{ | |
if(_timeDiff.Equals(TimeSpan.MinValue)) | |
{ | |
UpdateTimeDiff(); | |
} | |
if(_timeDiff.Equals(TimeSpan.MinValue)) | |
return DateTime.Now; | |
return DateTime.Now + -_timeDiff; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment