阻止控制台程序退出

阻止控制台程序退出的一个方法,取自 surging的服务端。

class Program
    {
        //用来阻止程序退出
        private static readonly ManualResetEvent _shutdownBlock = new ManualResetEvent(false);
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
       //启动其他线程
//Console.Read(); Console.CancelKeyPress += Console_CancelKeyPress; AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => {
          //等待退出信号触发 _shutdownBlock.WaitOne(); }; } //Ctrl+C 退出程序
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; _shutdownBlock.Set(); } }

 另:asp.net Core也是采用此方法

 参考:

https://github.com/dotnetcore/surging
surging/src/Surging.Core/Surging.Core.ServiceHosting/Internal/Implementation/ConsoleLifetime.cs

https://github.com/aspnet/AspNetCore
AspNetCore/src/Hosting/Hosting/src/Internal/WebHostLifetime.cs

--百转回魂
posted @ 2019-06-28 15:31  百转回魂  阅读(327)  评论(0编辑  收藏  举报