Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Context switching can affect timer triggering #4861

Merged
merged 2 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
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 @@ -194,6 +194,8 @@ internal void AddWaiter(Waiter waiter, long dueTime)
WakeWaiters();
}

internal event EventHandler? GateOpening;

private void WakeWaiters()
{
if (Interlocked.CompareExchange(ref _wakeWaitersGate, 1, 0) == 1)
Expand Down Expand Up @@ -234,13 +236,14 @@ private void WakeWaiters()
candidate = waiter;
}
}
}

if (candidate == null)
{
// didn't find a candidate to wake, we're done
_wakeWaitersGate = 0;
return;
if (candidate == null)
{
// didn't find a candidate to wake, we're done
GateOpening?.Invoke(this, EventArgs.Empty);
_wakeWaitersGate = 0;
return;
}
}

var oldTicks = _now.Ticks;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Time.Testing;
Expand Down Expand Up @@ -361,4 +362,31 @@ public void AdvanceTimeInCallback()

Assert.True(true, "Yay, we didn't enter an infinite loop!");
}

[Fact]
public void ShouldResetGateUnderLock_PreventingContextSwitching_AffectionOnTimerCallback()
{
// Arrange
var provider = new FakeTimeProvider { AutoAdvanceAmount = TimeSpan.FromSeconds(2) };
var calls = new List<object?>();
using var timer = provider.CreateTimer(calls.Add, "timer-1", TimeSpan.FromSeconds(3), TimeSpan.Zero);
var th = new Thread(() => provider.GetUtcNow());
provider.GateOpening += (_, _) =>
{
if (!th.IsAlive)
{
th.Start();
}

// use a timeout to prevent deadlock
th.Join(TimeSpan.FromMilliseconds(200));
};

// Act
provider.GetUtcNow();
th.Join();

// Assert
Assert.Single(calls);
}
}