如何在与终端分离时为单声道制作 cpu 友好的无限循环

How to make cpu-friendly infinite loop for mono when detached from terminal

我一直在我的自托管 ServiceStack 应用程序中使用这段代码来休眠 MainThread:

while (true)
{
    Console.ReadKey();
}

但是当应用程序从终端分离时它不起作用(例如由 start-stop-daemon 启动)因为这个错误:https://bugzilla.novell.com/show_bug.cgi?id=689976

作为快速解决方法,我已将代码更改为:

while (true)
{
    Thread.Sleep(100);
}

我看到 Thread.Sleep 不应该这样使用。

当应用程序与终端分离并且 运行 在单声道上时,如何正确冻结主线程?

如果您使用 linux(或其他 posix 系统),而不是使用 Console.ReadKey 您应该使用 ServiceStack wiki 上的 Mono.Posix library, as shown in the example 收听终止或终止信号:

        UnixSignal [] signals = new UnixSignal[] { 
            new UnixSignal(Signum.SIGINT), 
            new UnixSignal(Signum.SIGTERM), 
        };

        // Wait for a unix signal
        for (bool exit = false; !exit; )
        {
            int id = UnixSignal.WaitAny(signals);

            if (id >= 0 && id < signals.Length)
            {
                if (signals[id].IsSet) exit = true;
            }
        }