阻止控制台程序退出的一个方法,取自 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.cshttps://github.com/aspnet/AspNetCore
AspNetCore/src/Hosting/Hosting/src/Internal/WebHostLifetime.cs