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 结束对应进程
不触发任何事件