コード例 #1
0
        public void TestSyncedClock()
        {
            var clock0 = Clocks.SystemTicksClock;
            var clock1 = Clocks.SystemTicksClock.Adjust(+100);

            Debug.WriteLine($"Test1: time0: {clock0.Time}, time1: {clock1.Time}");
            Assert.AreEqual(clock0.Time, clock1.Time - 100, TimeUnit.Millisecond.ConvertTo(1, clock0.Unit));

            /* Manually synced */
            var synced = SyncedClock.Sync(clock0, clock1.Time);

            Debug.WriteLine($"Test2: synced: {clock0.Time}, time1: {clock1.Time}");
            Assert.AreEqual(synced.Time, clock1.Time, TimeUnit.Millisecond.ConvertTo(1, clock0.Unit));

            /* Delay garenteed */
            var random = new Random();

            Assert.IsFalse(SyncedClock.TrySync(clock0, () =>
            {
                SpinWait.SpinUntil(() => false, random.Next(110, 150));
                return(clock1.Time);
            }, TimeSpan.FromMilliseconds(5), 10, out _));
            Assert.IsTrue(SyncedClock.TrySync(clock0, () => clock1.Time, TimeSpan.FromMilliseconds(5), 15, out synced));
            Debug.WriteLine($"Test3: synced: {clock0.Time}, time1: {clock1.Time}");
            Assert.AreEqual(synced.Time, clock1.Time, TimeUnit.Millisecond.ConvertTo(6, clock0.Unit));
        }
コード例 #2
0
 public static bool TrySync([NotNull] IClock clock, Func <TimeUnit, long> remoteTimeSupplier, TimeSpan syncWithin, int maxRetryCount, out SyncedClock synced)
 {
     for (var i = maxRetryCount - 1; i >= 0; i--)
     {
         var startTicks   = clock.GetTicks();
         var remoteTime   = remoteTimeSupplier(clock.Unit);
         var endTicks     = clock.GetTicks();
         var elapsedTicks = endTicks - startTicks;
         if (elapsedTicks / 2 < syncWithin.Ticks)
         {
             synced = new SyncedClock(clock, TimeUnit.Tick.ConvertTo(startTicks, clock.Unit), remoteTime, 1);
             return(true);
         }
     }
     synced = null;
     return(false);
 }
コード例 #3
0
 public static bool TrySync([NotNull] IClock clock, Supplier <long> remoteTimeSupplier, TimeSpan syncWithin, int maxRetryCount, out SyncedClock synced)
 => TrySync(clock, unit => remoteTimeSupplier(), syncWithin, maxRetryCount, out synced);