Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.
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 @@ -3,6 +3,7 @@
<ProjectGuid>{ac20a28f-fda8-45e8-8728-058ead16e44c}</ProjectGuid>
<Configurations>netcoreapp-Debug;netcoreapp-Release;netstandard-Debug;netstandard-Release</Configurations>
<TestRuntime>true</TestRuntime>
<IncludeRemoteExecutor>true</IncludeRemoteExecutor>
</PropertyGroup>
<ItemGroup>
<Compile Include="TimerConstructorTests.cs" />
Expand All @@ -12,4 +13,9 @@
<ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
<Compile Include="TimerDisposeTests.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(CommonTestPath)\System\Threading\ThreadTestHelpers.cs">
<Link>CommonTest\System\Threading\ThreadTestHelpers.cs</Link>
</Compile>
</ItemGroup>
</Project>
54 changes: 54 additions & 0 deletions src/System.Threading.Timer/tests/TimerFiringTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tests;
using Xunit;
using Xunit.Sdk;

Expand Down Expand Up @@ -337,4 +338,57 @@ private static async Task PeriodAsync(int period, int iterations)
await tcs.Task.ConfigureAwait(false);
}
}

[Fact]
public void TimersCreatedConcurrentlyOnDifferentThreadsAllFire()
{
int processorCount = Environment.ProcessorCount;

int timerTickCount = 0;
TimerCallback timerCallback = _ => Interlocked.Increment(ref timerTickCount);

var threadStarted = new AutoResetEvent(false);
var createTimers = new ManualResetEvent(false);
var timers = new Timer[processorCount];
Action<object> createTimerThreadStart = data =>
{
int i = (int)data;
var sw = new Stopwatch();
threadStarted.Set();
createTimers.WaitOne();

// Use the CPU a bit around creating the timer to try to have some of these threads run concurrently
sw.Restart();
do
{
Thread.SpinWait(1000);
} while (sw.ElapsedMilliseconds < 10);

timers[i] = new Timer(timerCallback, null, 1, Timeout.Infinite);

// Use the CPU a bit around creating the timer to try to have some of these threads run concurrently
sw.Restart();
do
{
Thread.SpinWait(1000);
} while (sw.ElapsedMilliseconds < 10);
};

var waitsForThread = new Action[timers.Length];
for (int i = 0; i < timers.Length; ++i)
{
var t = ThreadTestHelpers.CreateGuardedThread(out waitsForThread[i], createTimerThreadStart);
t.IsBackground = true;
t.Start(i);
threadStarted.CheckedWait();
}

createTimers.Set();
ThreadTestHelpers.WaitForCondition(() => timerTickCount == timers.Length);

foreach (var waitForThread in waitsForThread)
{
waitForThread();
}
}
}