Can Unhandled Exceptions in Child AppDomains be prevented from crashing the main process?

前端 未结 1 1838
遇见更好的自我
遇见更好的自我 2021-01-18 00:31

I\'m writing a small plugins library which uses app domains to isolate plugins using .Net framework 4.0. Hence the code that goes in each plugin is out of my control. When a

1条回答
  •  太阳男子
    2021-01-18 00:45

    For handling WinForms exception. You could set "trap" for such ThreadExceptions in PluginBase class:

    public abstract class PluginBase:MarshalByRefObject
    {
        protected PluginBase()
        {
            System.Windows.Forms.Application.ThreadException +=
                (o, args) =>
                {
                    throw new Exception("UntrappedThread Exception:" + args.Exception);
                };
    
        }
    
        public abstract void ExecuteWinApp();
        public abstract void ExecuteThread();
    }
    

    As by default, it will show you "The Exception Window". But will got to this handler if provided.

    As for catching exception from other thread. There is no way. The best you could do is have a notification about Exception being thrown.

        AppDomain domain = AppDomain.CreateDomain("PluginDomain", null, domainSetup);
        domain.UnhandledException +=
            (o, eventArgs) =>
                {
                    Console.WriteLine("Exception was caught from other AppDomain: " + eventArgs.ExceptionObject);
                    Console.WriteLine("CLR is terminating?: " + eventArgs.IsTerminating);
                };
    

    0 讨论(0)
提交回复
热议问题