From 1a08680bddc37681c2c8cfee2b96ed2679db9c75 Mon Sep 17 00:00:00 2001 From: Cj Date: Wed, 20 Nov 2024 16:03:54 +0000 Subject: [PATCH] Basic memory manager (!177) Attempt at slowing down the memory leak caused by bots spawning/dying Co-authored-by: Cj <161484149+CJ-SPT@users.noreply.github.com> Reviewed-on: https://dev.sp-tarkov.com/SPT/Modules/pulls/177 Co-authored-by: Cj Co-committed-by: Cj --- project/SPT.Custom/SPTCustomPlugin.cs | 5 ++++ project/SPT.Custom/Utils/MemoryManager.cs | 36 +++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 project/SPT.Custom/Utils/MemoryManager.cs diff --git a/project/SPT.Custom/SPTCustomPlugin.cs b/project/SPT.Custom/SPTCustomPlugin.cs index 22f3674..984b787 100644 --- a/project/SPT.Custom/SPTCustomPlugin.cs +++ b/project/SPT.Custom/SPTCustomPlugin.cs @@ -5,15 +5,19 @@ using SPT.Custom.Utils; using SPT.Reflection.Utils; using BepInEx; using UnityEngine; +using BepInEx.Logging; namespace SPT.Custom { [BepInPlugin("com.SPT.custom", "SPT.Custom", SPTPluginInfo.PLUGIN_VERSION)] public class SPTCustomPlugin : BaseUnityPlugin { + internal static ManualLogSource Log; + public void Awake() { Logger.LogInfo("Loading: SPT.Custom"); + Log = Logger; try { @@ -44,6 +48,7 @@ namespace SPT.Custom //new AllowAirdropsInPvEPatch().Enable(); HookObject.AddOrGetComponent(); + HookObject.AddOrGetComponent(); } catch (Exception ex) { diff --git a/project/SPT.Custom/Utils/MemoryManager.cs b/project/SPT.Custom/Utils/MemoryManager.cs new file mode 100644 index 0000000..b42a5a0 --- /dev/null +++ b/project/SPT.Custom/Utils/MemoryManager.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections; +using System.Threading.Tasks; +using UnityEngine; +using UnityEngine.Scripting; + +namespace SPT.Custom.Utils; + +public class MemoryManager : MonoBehaviour +{ + private WaitForSecondsRealtime _gcCollectionTime = new(30f); + + public void Awake() + { + StartCoroutine(MemoryManagerCoroutine()); + } + + private IEnumerator MemoryManagerCoroutine() + { + yield return _gcCollectionTime; + + // SPTCustomPlugin.Log.LogDebug($"Allocated Mananged Memory {GC.GetTotalMemory(false) / 1024f / 1024f} MB"); + + Task.Run(CollectMemory); + + StartCoroutine(MemoryManagerCoroutine()); + } + + private Task CollectMemory() + { + GarbageCollector.GCMode = GarbageCollector.Mode.Enabled; + GC.Collect(2, GCCollectionMode.Optimized, false, false); + + return Task.CompletedTask; + } +} \ No newline at end of file