How to prevent an exception in a background thread from terminating an application?

后端 未结 5 1114
我寻月下人不归
我寻月下人不归 2020-11-29 22:33

I can hookup to AppDomain.CurrentDomain.UnhandledException to log exceptions from background threads, but how do I prevent them terminating the runtime?

5条回答
  •  迷失自我
    2020-11-29 22:43

    Keeping the answer short, yes, you do can prevent the runtime from terminating.

    Here is a demo of the workaround:

    class Program
    {
        void Run()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    
            Console.WriteLine("Press enter to exit.");
    
            do
            {
                (new Thread(delegate()
                {
                    throw new ArgumentException("ha-ha");
                })).Start();
    
            } while (Console.ReadLine().Trim().ToLowerInvariant() == "x");
    
    
            Console.WriteLine("last good-bye");
        }
    
        int r = 0;
    
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Interlocked.Increment(ref r);
            Console.WriteLine("handled. {0}", r);
            Console.WriteLine("Terminating " + e.IsTerminating.ToString());
    
            Thread.CurrentThread.IsBackground = true;
            Thread.CurrentThread.Name = "Dead thread";            
    
            while (true)
                Thread.Sleep(TimeSpan.FromHours(1));
            //Process.GetCurrentProcess().Kill();
        }
    
        static void Main(string[] args)
        {
            Console.WriteLine("...");
            (new Program()).Run();
        }
    }
    

    Essentially, you just did not let the runtime to show the "... program has stopped working" dialog.

    In case you need to log the exception and silently exit, you can call Process.GetCurrentProcess().Kill();

提交回复
热议问题