Skip to content

Commit 4d9fecc

Browse files
committed
Hook Main.ReadLineInput to add thread delay to prevent high cpu usage when ReadLine returns null
This can occur in some docker setups
1 parent 04763d2 commit 4d9fecc

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

TerrariaServerAPI/TerrariaApi.Server/Hooking/ServerHooks.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ public static void AttachTo(HookManager hookManager)
1818
_hookManager = hookManager;
1919

2020
HookEvents.Terraria.Main.startDedInput += Main_startDedInput;
21+
HookEvents.Terraria.Main.ReadLineInput += Main_ReadLineInput;
2122
HookEvents.Terraria.RemoteClient.Reset += RemoteClient_Reset;
2223
Hooks.Main.CommandProcess += OnProcess;
2324
}
@@ -36,6 +37,23 @@ static void Main_startDedInput(object? sender, HookEvents.Terraria.Main.startDed
3637
args.OriginalMethod();
3738
}
3839

40+
#nullable enable
41+
/// <summary>
42+
/// Hooks the default ReadLineInput method to add a small delay when Console.ReadLine() returns null.
43+
/// For example, some docker instances may experience a 100% CPU usage due to this vanilla thread implementation.
44+
/// </summary>
45+
static void Main_ReadLineInput(object? sender, HookEvents.Terraria.Main.ReadLineInputEventArgs args)
46+
{
47+
args.ContinueExecution = false;
48+
49+
string? text;
50+
while ((text = Console.ReadLine()) is null)
51+
System.Threading.Thread.Sleep(100);
52+
53+
args.HookReturnValue = text;
54+
}
55+
#nullable disable
56+
3957
static void OnProcess(object sender, Hooks.Main.CommandProcessEventArgs e)
4058
{
4159
if (e.Result == HookResult.Cancel)

0 commit comments

Comments
 (0)