DotNext by .NET Foundation and Contributors

<PackageReference Include="DotNext" Version="5.16.0" />

 GCLatencyModeScope

Represents lexical scope of the specific GC latency mode.
using System; using System.Runtime; using System.Runtime.InteropServices; namespace DotNext.Runtime { [StructLayout(LayoutKind.Auto)] public readonly struct GCLatencyModeScope : IDisposable { private readonly GCLatencyMode? currentMode; public static GCLatencyModeScope SustainedLowLatency => new GCLatencyModeScope(GCLatencyMode.SustainedLowLatency); public static GCLatencyModeScope LowLatency => new GCLatencyModeScope(GCLatencyMode.LowLatency); public GCLatencyModeScope(GCLatencyMode mode) { currentMode = GCSettings.LatencyMode; GCSettings.LatencyMode = mode; } public void Dispose() { if (currentMode.HasValue) GCSettings.LatencyMode = currentMode.GetValueOrDefault(); } } }