From b2736e880ff36efbbe7be2e5aa8f3f51a4ced801 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Breu=C3=9F=20Valentin?= Date: Fri, 30 Oct 2026 08:03:28 +0100 Subject: [PATCH] fix: measure a mocked timer's due time from when it is started TimerMock read the clock for the first due time on its background thread, after Start() had already returned. When that thread was scheduled late, a clock advance made right after creating or changing the timer was counted before the due time started, so with auto-advance disabled the timer waited for a time that never came. This made TimerMockTests.DisableAutoAdvance_ShouldStartTimerWhenTimeElapsed time out on net48 on Windows CI. The clock is now read on the calling thread, matching the real Timer and PeriodicTimerMock, which measure from construction. --- .../TimeSystem/TimerMock.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Source/Testably.Abstractions.Testing/TimeSystem/TimerMock.cs b/Source/Testably.Abstractions.Testing/TimeSystem/TimerMock.cs index 43550a3c4..02d303081 100644 --- a/Source/Testably.Abstractions.Testing/TimeSystem/TimerMock.cs +++ b/Source/Testably.Abstractions.Testing/TimeSystem/TimerMock.cs @@ -235,9 +235,9 @@ internal void RegisterOnDispose(Action? onDispose) } #pragma warning disable S3776 // Cognitive Complexity of methods should not be too high - private async Task RunTimer(CancellationToken cancellationToken = default) + private async Task RunTimer(long startTicks, CancellationToken cancellationToken = default) { - long nextPlannedExecution = _mockTimeSystem.TimeProvider.ElapsedTicks + _dueTime.Ticks; + long nextPlannedExecution = startTicks + _dueTime.Ticks; if (_dueTime.TotalMilliseconds < 0) { @@ -330,6 +330,9 @@ private void Start() } CancellationToken token = runningCancellationTokenSource.Token; + // Read the clock on the calling thread, as the due time is relative to the call; reading it + // on the background thread would miss a time change before that thread is scheduled. + long startTicks = _mockTimeSystem.TimeProvider.ElapsedTicks; using ManualResetEventSlim startCreateTimerThreads = new(); _ = Task.Run( async () => @@ -344,7 +347,7 @@ private void Start() // Ignore any ObjectDisposedException } - await RunTimer(token).ConfigureAwait(false); + await RunTimer(startTicks, token).ConfigureAwait(false); }, cancellationToken: token) .ContinueWith(_ =>