From 4d9fecc5cdca99e60db3a297d39752edca900243 Mon Sep 17 00:00:00 2001 From: Luke Date: Sat, 7 Mar 2026 22:31:07 +1000 Subject: [PATCH] Hook Main.ReadLineInput to add thread delay to prevent high cpu usage when ReadLine returns null This can occur in some docker setups --- .../TerrariaApi.Server/Hooking/ServerHooks.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/TerrariaServerAPI/TerrariaApi.Server/Hooking/ServerHooks.cs b/TerrariaServerAPI/TerrariaApi.Server/Hooking/ServerHooks.cs index 2392f0d5..0db2f9d2 100644 --- a/TerrariaServerAPI/TerrariaApi.Server/Hooking/ServerHooks.cs +++ b/TerrariaServerAPI/TerrariaApi.Server/Hooking/ServerHooks.cs @@ -18,6 +18,7 @@ public static void AttachTo(HookManager hookManager) _hookManager = hookManager; HookEvents.Terraria.Main.startDedInput += Main_startDedInput; + HookEvents.Terraria.Main.ReadLineInput += Main_ReadLineInput; HookEvents.Terraria.RemoteClient.Reset += RemoteClient_Reset; Hooks.Main.CommandProcess += OnProcess; } @@ -36,6 +37,23 @@ static void Main_startDedInput(object? sender, HookEvents.Terraria.Main.startDed args.OriginalMethod(); } +#nullable enable + /// + /// Hooks the default ReadLineInput method to add a small delay when Console.ReadLine() returns null. + /// For example, some docker instances may experience a 100% CPU usage due to this vanilla thread implementation. + /// + static void Main_ReadLineInput(object? sender, HookEvents.Terraria.Main.ReadLineInputEventArgs args) + { + args.ContinueExecution = false; + + string? text; + while ((text = Console.ReadLine()) is null) + System.Threading.Thread.Sleep(100); + + args.HookReturnValue = text; + } +#nullable disable + static void OnProcess(object sender, Hooks.Main.CommandProcessEventArgs e) { if (e.Result == HookResult.Cancel)