0

I tried to execute a function when closing the program it works when I do CTRL + C but when I close it with the "X" the function is not fully executed.

So I would like to know if you know why and if so how to fix the problem.

I tried to do what is mentioned on this page Capture console exit C#.

Thank you in advance for your answers.

        static void Main(string[] args)
        {
            _handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(_handler, true);   
        }
        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)
        {
            example();

            exitSystem = true;

            Environment.Exit(-1);

            return true;
        }

        public static bool exitSystem = false;

        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

        private delegate bool EventHandler(CtrlType sig);
        static EventHandler _handler;
        public static void example()
        {
            for (int i = 0; i < 250000; i++)
                Console.WriteLine(i);
        }
Fanfarone
  • 131
  • 1
  • 7
  • 1
    The OS applies a time-out on the handler function. If it takes more than 5 seconds then it forcibly terminates the program. example() is too silly to be practical and takes too long. – Hans Passant May 03 '20 at 09:21
  • And there's no way to extend that? – Fanfarone May 03 '20 at 09:29
  • 1
    There is no (public) API call to modify this timeout. Check out [this answer](https://stackoverflow.com/a/47041556/3013249) – MrPaulch May 03 '20 at 09:39

0 Answers0