c# processsexit事件处理程序没有触发代码

本文关键字:代码 processsexit 事件处理 程序 | 更新日期: 2023-09-27 18:17:10

我有一个小函数,我想在我的进程退出时调用,但是,在关闭时(通过红色退出按钮)该函数将不会执行。

我的代码如下:
namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var callback = new InstanceContext(new ClientCallback());
            var client = new MyServiceClient(callback);
            client.Open();
            client.Register();
            AppDomain.CurrentDomain.ProcessExit += (sender, EventArgs) =>
            {
                client.checkOut();
            };
            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
            client.checkOut();
            client.Close();
        }
    }
}

c# processsexit事件处理程序没有触发代码

using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            HandlerRoutine hr = new HandlerRoutine(InspectControlType);
            SetConsoleCtrlHandler(hr, true);
            Console.WriteLine("Click on Windows Close Button");
            Console.ReadLine();
        }
        [DllImport("Kernel32")]
        public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
        public delegate bool HandlerRoutine(ControlTypes CtrlType);
        public enum ControlTypes
        {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT,
            CTRL_CLOSE_EVENT,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT
        }
        private static bool InspectControlType(ControlTypes ctrlType)
        {
            Console.WriteLine("Hello You choose to end this program.Do you really want to close? :" + ctrlType.ToString());
            Console.ReadLine();
            return true;
        }

    }
}