Skip to content

Commit

Permalink
Use a semaphore instead of a cancellation token to halt the main thread
Browse files Browse the repository at this point in the history
  • Loading branch information
nexus4880 committed Dec 19, 2024
1 parent 81da2dd commit 7994ecf
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 38 deletions.
13 changes: 6 additions & 7 deletions Fuyu.Backend/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
39 changes: 8 additions & 31 deletions Fuyu.Common/IO/Terminal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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)
{
Expand All @@ -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);
};
}
}

Expand Down

0 comments on commit 7994ecf

Please sign in to comment.