How to detect when application terminates?

前端 未结 5 792
我寻月下人不归
我寻月下人不归 2020-12-07 14:52

This is a follow up to my initial question and I would like to present my findings and ask for corrections, ideas and insights. My findings (or rather interpretations) come

5条回答
  •  鱼传尺愫
    2020-12-07 15:04

    You write:

    System.AppDomain.CurrentDomain.UnhandledException: (if handled in default AppDomain:) raised for any unhandled exception in any thread, no matter what AppDomain the thread started in. This means, this can be used as the catch-all for all unhandled exceptions.

    I do not think that this is correct. Try the following code:

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace AppDomainTestingUnhandledException
    {
        class Program
        {
            static void Main(string[] args)
            {
                AppDomain.CurrentDomain.UnhandledException +=
                    (sender, eventArgs) => Console.WriteLine("Something went wrong! " + args);
    
                var ad = AppDomain.CreateDomain("Test");
    
                var service =
                    (RunInAnotherDomain)
                    ad.CreateInstanceAndUnwrap(
                        typeof(RunInAnotherDomain).Assembly.FullName, typeof(RunInAnotherDomain).FullName);
    
                try
                {
                    service.Start();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Crash: " + e.Message);
                }
                finally
                {
                    AppDomain.Unload(ad);
                }
            }
        }
    
        class RunInAnotherDomain : MarshalByRefObject
        {
            public void Start()
            {
                Task.Run(
                    () =>
                        {
                            Thread.Sleep(1000);
                            Console.WriteLine("Uh oh!");
                            throw new Exception("Oh no!");
                        });
    
                while (true)
                {
                    Console.WriteLine("Still running!");
                    Thread.Sleep(300);
                }
            }
        }
    }
    

    As far as I can tell, the UnhandledException handler is never called, and the thread will just silently crash (or nag at you if you run it in the debugger).

提交回复
热议问题