From 7994ecfb21698896fd32642e5ea597c76b838a60 Mon Sep 17 00:00:00 2001 From: nexus4880 <38168516+nexus4880@users.noreply.github.com> Date: Wed, 18 Dec 2024 17:57:14 -0700 Subject: [PATCH] Use a semaphore instead of a cancellation token to halt the main thread --- Fuyu.Backend/Program.cs | 13 ++++++------- Fuyu.Common/IO/Terminal.cs | 39 ++++++++------------------------------ 2 files changed, 14 insertions(+), 38 deletions(-) diff --git a/Fuyu.Backend/Program.cs b/Fuyu.Backend/Program.cs index 19df7982..80f98d4a 100644 --- a/Fuyu.Backend/Program.cs +++ b/Fuyu.Backend/Program.cs @@ -33,13 +33,12 @@ static async Task Main() await ModManager.Instance.Load(container); - using (var cts = new CancellationTokenSource()) - { - Terminal.WaitForInput(cts); - Terminal.WriteLine("WaitOne start"); - cts.Token.WaitHandle.WaitOne(); - Terminal.WriteLine("WaitOne finished"); - } + var semaphore = new SemaphoreSlim(0); + + Terminal.WaitForInput(semaphore); + Terminal.WriteLine("WaitOne start"); + await semaphore.WaitAsync(); + Terminal.WriteLine("WaitOne finished"); Terminal.WriteLine("Unloading"); await ModManager.Instance.UnloadAll(); diff --git a/Fuyu.Common/IO/Terminal.cs b/Fuyu.Common/IO/Terminal.cs index 141f07bf..e7ce07e9 100644 --- a/Fuyu.Common/IO/Terminal.cs +++ b/Fuyu.Common/IO/Terminal.cs @@ -8,11 +8,6 @@ public static class Terminal { private static object _lock = new object(); - // NOTE: this exists because ProcessExit gets called after CancelKeyPress - // when Main disposes of CancellationTokenSource so this is my fix - // -- nexus4880, 2024-12-12 - private static bool _closing; - public static void WriteLine(string text) { var line = $"{text}\n"; @@ -34,7 +29,7 @@ public static void WriteLine(object o) WriteLine(o.ToString()); } - public static void WaitForInput(CancellationTokenSource cts) + public static void WaitForInput(SemaphoreSlim semaphore) { if (Environment.GetEnvironmentVariable(EnvironmentVariables.Docker) == null) { @@ -44,41 +39,23 @@ public static void WaitForInput(CancellationTokenSource cts) Console.In.ReadLine(); lock (_lock) - { - if (!_closing) - { - cts.Cancel(); - _closing = true; - } - } + { + semaphore.Release(1); + } } else { WriteLine("(WaitForInput) Docker"); AppDomain.CurrentDomain.ProcessExit += (_, __) => - { - lock (_lock) - { - if (!_closing) - { - cts.Cancel(); - _closing = true; - } - } + { + semaphore.Release(1); }; Console.CancelKeyPress += (_, e) => { e.Cancel = true; - lock (_lock) - { - if (!_closing) - { - cts.Cancel(); - _closing = true; - } - } - }; + semaphore.Release(1); + }; } }