using System; using System.Diagnostics; using System.Runtime; using System.Runtime.InteropServices; namespace XFE.SeAgent.Plugin.Performance { internal sealed class GcLatencyTuning : IDisposable { [StructLayout(LayoutKind.Sequential)] private struct MemoryStatus { public uint Size, Load; public ulong TotalPhysical, AvailablePhysical, TotalPageFile, AvailablePageFile, TotalVirtual, AvailableVirtual, Extended; } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GlobalMemoryStatusEx(ref MemoryStatus memory); private GCLatencyMode previous; private long lastCheck; private bool externalOverride; public bool Enabled { get; private set; } public bool Applied { get; private set; } public string Reason { get; private set; } = "disabled"; public ulong AvailableBytes { get; private set; } public void Set(bool enabled) { if (enabled == Enabled) return; Enabled = enabled; externalOverride = false; lastCheck = 0; if (!enabled) { Restore(); Reason = "disabled"; } } public void Update(bool playing) { if (!Enabled || !playing) { Restore(); if (Enabled) Reason = "outside active gameplay"; return; } long now = Stopwatch.GetTimestamp(); if (now - lastCheck < Stopwatch.Frequency) return; lastCheck = now; if (Applied && GCSettings.LatencyMode != GCLatencyMode.SustainedLowLatency) { Applied = false; externalOverride = true; } if (externalOverride) { Reason = "another component changed GC latency; toggle to reapply"; return; } var memory = new MemoryStatus { Size = (uint)Marshal.SizeOf(typeof(MemoryStatus)) }; if (!GlobalMemoryStatusEx(ref memory)) { Restore(); Reason = "memory status unavailable"; return; } AvailableBytes = memory.AvailablePhysical; if (memory.AvailablePhysical < Math.Max(2UL * 1024 * 1024 * 1024, memory.TotalPhysical / 10)) { Restore(); Reason = "low available memory"; return; } if (!Applied) { var mode = GCSettings.LatencyMode; if (mode == GCLatencyMode.NoGCRegion || mode == GCLatencyMode.SustainedLowLatency) { Reason = "existing GC mode is owned by another component"; return; } previous = mode; GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency; Applied = true; } Reason = "active"; } private void Restore() { if (!Applied) return; if (GCSettings.LatencyMode == GCLatencyMode.SustainedLowLatency) GCSettings.LatencyMode = previous; Applied = false; } public void Dispose() { Restore(); } } }