2009-06-12 5 views
9

Nous allons Asume le bit folowing de code, ce qui vous permet d'appeler une classe dans une autre AppDomain et gérer presque toute exception:Gestion des exceptions critiques dans différents domaines d'application

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Reflection; 

namespace MyAppDomain 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     AppDomain myDomain = null; 
     try 
     { 
     myDomain = AppDomain.CreateDomain("Remote Domain"); 
     myDomain.UnhandledException += new UnhandledExceptionEventHandler(myDomain_UnhandledException); 
     Worker remoteWorker = (Worker)myDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Worker).FullName); 
     remoteWorker.VeryBadMethod(); 
     } 
     catch(Exception ex) 
     { 
     myDomain_UnhandledException(myDomain, new UnhandledExceptionEventArgs(ex, false)); 
     } 
     finally 
     { 
     if (myDomain != null) 
      AppDomain.Unload(myDomain); 
     } 

     Console.ReadLine(); 
    } 

    static void myDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
    { 
     Exception ex = e.ExceptionObject as Exception; 
     if (ex != null) 
     Console.WriteLine(ex.Message); 
     else 
     Console.WriteLine("A unknown exception was thrown"); 
    } 
    } 

    public class Worker : MarshalByRefObject 
    { 
    public Worker() 
    { 

    } 

    public string DomainName 
    { 
     get 
     { 
     return AppDomain.CurrentDomain.FriendlyName; 
     } 
    } 

    public void VeryBadMethod() 
    { 
     // Autch! 
     throw new InvalidOperationException(); 
    } 

    } 
} 

Maintenant, le problème est, allmost tout exception peut être gérée, pas toutes les exceptions. Une exception StackOverflowException, par exemple, plantera toujours le processus. Existe-t-il un moyen de détecter les exceptions critiques dans différents domaines d'application et de les gérer en déchargeant AppDomain, tout en permettant à d'autres domaines d'application de continuer?

Répondre

2

Malheureusement, une exception StackOverflowException ne peut pas être interceptée.

Voir: http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

... A partir du .NET Framework version 2.0 , un objet StackOverflowException ne peut pas être pris par un try-catch bloc et le processus correspondant est terminé par défaut . ...

Mise à jour:

Après une enquête plus poussée dans mes vieilles questions que je trouve ce vieux fil: http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=36073