Skip to content
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Guard the pressure helper reflection with a test
  • Loading branch information
ApparentlyPlus committed Aug 24, 2026
commit 09eed12b21c32c835c1836cd2dec36e955ccf53b
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ public void BuffersAreCollectedWhenStale()

private static bool IsStressModeEnabledAndRemoteExecutorSupported => TestEnvironment.IsStressModeEnabled && RemoteExecutor.IsSupported;

private static readonly MethodInfo? s_pressureMethod =
Comment thread
ApparentlyPlus marked this conversation as resolved.
Resolved
Type.GetType("System.Buffers.Utilities, System.Private.CoreLib")
?.GetMethod("GetMemoryPressure", BindingFlags.Static | BindingFlags.NonPublic, Type.EmptyTypes);
Comment thread
ApparentlyPlus marked this conversation as resolved.
Resolved
Comment thread
ApparentlyPlus marked this conversation as resolved.
Resolved

// ThreadLocalIsCollectedUnderHighPressure only runs under DOTNET_TEST_STRESS=1, so without
// this, the private API it reflects on could change without anything noticing.
[Fact]
public void MemoryPressureHelperIsAvailable()
{
Assert.NotNull(s_pressureMethod);
}

// This test can cause problems for other tests run in parallel (from other assemblies) as
// it pushes the physical memory usage above 80% temporarily.
[ConditionalFact(typeof(CollectionTests), nameof(IsStressModeEnabledAndRemoteExecutorSupported))]
Expand All @@ -94,21 +106,7 @@ public unsafe void ThreadLocalIsCollectedUnderHighPressure()
const int AllocSize = 1024 * 1024 * 64;
int PageSize = Environment.SystemPageSize;

Type utilitiesType = typeof(ArrayPool<byte>).Assembly.GetType("System.Buffers.Utilities");
Assert.NotNull(utilitiesType);

MethodInfo pressureMethod = utilitiesType.GetMethod("GetMemoryPressure", BindingFlags.Static | BindingFlags.NonPublic);
Assert.NotNull(pressureMethod);

Type pressureType = utilitiesType.GetNestedType("MemoryPressure", BindingFlags.NonPublic);
Assert.NotNull(pressureType);

// The loop below only terminates once the helper reports High, so bail out early
// if its signature ever changes rather than allocating forever.
Assert.Empty(pressureMethod.GetParameters());
Assert.Equal(pressureType, pressureMethod.ReturnType);

object highPressure = Enum.Parse(pressureType, "High");
object highPressure = Enum.Parse(s_pressureMethod.ReturnType, "High");

do
{
Expand All @@ -121,7 +119,7 @@ public unsafe void ThreadLocalIsCollectedUnderHighPressure()
}

GC.Collect(2);
} while (!highPressure.Equals(pressureMethod.Invoke(null, null)));
} while (!highPressure.Equals(s_pressureMethod.Invoke(null, null)));

GC.WaitForPendingFinalizers();

Expand Down
Loading