Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -112,20 +112,46 @@ static WeakReference<PeriodicTimer> Create() =>
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public async Task PeriodicTimer_ActiveOperations_TimerRooted()
{
(WeakReference<PeriodicTimer> timer, ValueTask<bool> task) = Create();
// Step 1: Verify that if we have an active wait the timer does not get collected.
WeakReference<PeriodicTimer> timer = await CreateAndVerifyRooted();

WaitForTimerToBeCollected(timer, expected: false);
// Step 2: Verify that now the timer does get collected
WaitForTimerToBeCollected(timer, expected: true);

Assert.True(await task);
// It is important that we do these two things in NoInlining
// methods. We are only guaranteed that references inside these
// methods are not live anymore when the functions return.
[MethodImpl(MethodImplOptions.NoInlining)]
static async ValueTask<WeakReference<PeriodicTimer>> CreateAndVerifyRooted()
{
(WeakReference<PeriodicTimer> timer, ValueTask<bool> task) = CreateActive();

WaitForTimerToBeCollected(timer, expected: true);
WaitForTimerToBeCollected(timer, expected: false);

Assert.True(await task);

return timer;
}

[MethodImpl(MethodImplOptions.NoInlining)]
static (WeakReference<PeriodicTimer>, ValueTask<bool>) Create()
static (WeakReference<PeriodicTimer>, ValueTask<bool>) CreateActive()
{
var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(1));
ValueTask<bool> task = timer.WaitForNextTickAsync();
return (new WeakReference<PeriodicTimer>(timer), task);
int waitMs = 1;
for (int i = 0; i < 10; i++)
{
var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(waitMs));
ValueTask<bool> task = timer.WaitForNextTickAsync();
if (!task.IsCompleted)
{
return (new WeakReference<PeriodicTimer>(timer), task);
}

task.GetAwaiter().GetResult();

waitMs *= 2;
}

throw new Exception("Expected to be able to create an active wait for a timer");
}
}

Expand Down