处理不同appdomains中的关键异常

Jer*_*eer 9 c#

让我们假设下面的代码,它允许您在不同的AppDomain中调用一个类并处理几乎所有异常:

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();
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

现在问题是,几乎所有异常都可以处理,而不是每个例外.例如,StackOverflowException仍会使进程崩溃.有没有办法检测不同appdomains中的关键异常,并通过卸载AppDomain来处理这些异常,但仍然允许其他AppDomain继续?

小智 2

不幸的是,无法捕获 StackOverflowException。

请参阅:http ://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

...从 .NET Framework 2.0 版开始,StackOverflowException 对象无法被 try-catch 块捕获,并且默认情况下会终止相应的进程。...

更新:

在进一步调查我的旧问题后,我发现了这个旧线程: http://www.c-sharpcorner.com/Forums/ShowMessages.aspx ?ThreadID=36073