1. 程式人生 > 其它 >dotnet core Console事件處理機制

dotnet core Console事件處理機制

class Program
    {
        static TextFileLog log = new TextFileLog();
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
            AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
            AssemblyLoadContext.Default.Unloading += unloadTask;//1
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;//2
            Process.GetCurrentProcess().Exited += Program_Exited;
            try
            {
 
                log.WriteLine("123");
                Console.WriteLine($"...");
 
                Thread.Sleep(-1);
            }
            catch (Exception ex)
            {
                log.WriteLine(ex + "");
            }
            Console.WriteLine("ok!");
            //var rstr = Console.ReadLine();
            //XTrace.WriteLine($"rstr={rstr}");
        }
 
        private static void Program_Exited(object sender, EventArgs e)
        {
            log.WriteLine("1");
            Thread.Sleep(2 * 1000);
            log.WriteLine("Program_Exited");
        }
 
        private static void unloadTask(AssemblyLoadContext obj)
        {
            log.WriteLine("2");
            Thread.Sleep(15 * 1000);
            log.WriteLine("Unloading");
        }
 
        private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            log.WriteLine("3");
            //Thread.Sleep(15 * 1000);
            log.WriteLine($"CurrentDomain_ProcessExit!!!");
        }
 
        private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
        {
            log.WriteLine("CurrentDomain_FirstChanceException raised in {0}: {1}", AppDomain.CurrentDomain.FriendlyName, e.Exception);
        }
 
        private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
        {
            log.WriteLine($"CurrentDomain_DomainUnload!!!");
        }
 
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;
            if (ex != null)
            {
                log.WriteLine($"CurrentDomain_UnhandledException-{ex}");
            }
        }
    }

  

結論:

1.CentOS7下

1.1 nohup執行,終端呼叫kill pid時會觸發

AssemblyLoadContext.Default.Unloading
AppDomain.CurrentDomain.ProcessExit

事件耗時測試為10s

2.Win10下

2.1 點X關閉

不會觸發任何事件

2.2 結束對應程序

不觸發任何事件