为了账号安全,请及时绑定邮箱和手机立即绑定

捕获控制台退出C#

捕获控制台退出C#

30秒到达战场 2019-06-26 16:52:29
捕获控制台退出C#我有一个控制台应用程序,其中包含了相当多的线程。有些线程监视某些条件,如果它们是真,则终止程序。这种终止可以在任何时候发生。我需要一个可以在程序关闭时触发的事件,以便清理所有其他线程并正确关闭所有文件句柄和连接。我不确定.NET框架中是否已经内置了一个,所以我在编写自己的框架之前先问一下。我想知道是否有这样的活动:MyConsoleProgram.OnExit += CleanupBeforeExit;
查看完整描述

3 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

完整的示例,使用ctrl-c,用X关闭窗口并杀死:

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading;namespace TestTrapCtrlC {
    public class Program {
        static bool exitSystem = false;

        #region Trap application termination
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;

        enum CtrlType {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT = 1,
            CTRL_CLOSE_EVENT = 2,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT = 6
        }

        private static bool Handler(CtrlType sig) {
            Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");

            //do your cleanup here
            Thread.Sleep(5000); //simulate some cleanup delay

            Console.WriteLine("Cleanup complete");

            //allow main to run off
            exitSystem = true;

            //shutdown right away so there are no lingering threads
            Environment.Exit(-1);

            return true;
        }
        #endregion

        static void Main(string[] args) {
            // Some boilerplate to react to close window event, CTRL-C, kill, etc
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);

            //start your multi threaded program here
            Program p = new Program();
            p.Start();

            //hold the console so it doesn’t run off the end
            while (!exitSystem) {
                Thread.Sleep(500);
            }
        }

        public void Start() {
            // start a thread and start doing some processing
            Console.WriteLine("Thread started, processing..");
        }
    }}


查看完整回答
反对 回复 2019-06-26
?
萧十郎

TA贡献1815条经验 获得超12个赞

有WinForms应用程序;

Application.ApplicationExit += CleanupBeforeExit;

对于控制台应用程序,请尝试

AppDomain.CurrentDomain.DomainUnload += CleanupBeforeExit;

但是我不确定在什么时候调用它,或者它是否在当前域中工作。我怀疑不是。


查看完整回答
反对 回复 2019-06-26
  • 3 回答
  • 0 关注
  • 809 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信