Skip to content

Commit

Permalink
Make the TimeProvider timer rest reliable (#106303)
Browse files Browse the repository at this point in the history
  • Loading branch information
tarekgh authored Aug 13, 2024
1 parent ec7fd04 commit 8e0927f
Showing 1 changed file with 8 additions and 12 deletions.
20 changes: 8 additions & 12 deletions src/libraries/Common/tests/System/TimeProviderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,13 @@ public void TestSystemTimestamp()

public static IEnumerable<object[]> TimersProvidersData()
{
yield return new object[] { TimeProvider.System, 6000 };
yield return new object[] { new FastClock(), 3000 };
yield return new object[] { TimeProvider.System, 1200 }; // At least 4-periods of of 300ms
yield return new object[] { new FastClock(), 600 }; // At least 4-periods of of 150ms. fast clock cut time by half
}

[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[MemberData(nameof(TimersProvidersData))]
public void TestProviderTimer(TimeProvider provider, int MaxMilliseconds)
public void TestProviderTimer(TimeProvider provider, int minMilliseconds)
{
TimerState state = new TimerState();

Expand All @@ -122,8 +122,6 @@ public void TestProviderTimer(TimeProvider provider, int MaxMilliseconds)
{
s.Counter++;

s.TotalTicks += DateTimeOffset.UtcNow.Ticks - s.UtcNow.Ticks;

switch (s.Counter)
{
case 2:
Expand All @@ -132,12 +130,11 @@ public void TestProviderTimer(TimeProvider provider, int MaxMilliseconds)
break;

case 4:
s.Stopwatch.Stop();
s.TokenSource.Cancel();
s.Timer.Dispose();
break;
}

s.UtcNow = DateTimeOffset.UtcNow;
}
},
state,
Expand All @@ -148,7 +145,7 @@ public void TestProviderTimer(TimeProvider provider, int MaxMilliseconds)

Assert.Equal(4, state.Counter);
Assert.Equal(400, state.Period);
Assert.True(MaxMilliseconds >= state.TotalTicks / TimeSpan.TicksPerMillisecond, $"The total fired periods {state.TotalTicks / TimeSpan.TicksPerMillisecond}ms expected not exceeding the expected max {MaxMilliseconds}");
Assert.True(minMilliseconds <= state.Stopwatch.ElapsedMilliseconds, $"The total fired periods {state.Stopwatch.ElapsedMilliseconds}ms expected to be greater then the expected min {minMilliseconds}ms");
}

[Fact]
Expand Down Expand Up @@ -459,17 +456,16 @@ public TimerState()
{
Counter = 0;
Period = 300;
TotalTicks = 0;
UtcNow = DateTimeOffset.UtcNow;
TokenSource = new CancellationTokenSource();
Stopwatch = new Stopwatch ();
Stopwatch.Start();
}

public CancellationTokenSource TokenSource { get; set; }
public int Counter { get; set; }
public int Period { get; set; }
public DateTimeOffset UtcNow { get; set; }
public ITimer Timer { get; set; }
public long TotalTicks { get; set; }
public Stopwatch Stopwatch { get; set; }
};

// Clock that speeds up the reported time
Expand Down

0 comments on commit 8e0927f

Please sign in to comment.