C# 处理不同AppDomain中的关键异常

C# 处理不同AppDomain中的关键异常,c#,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 =

让我们分析一下下面的代码,它允许您在不同的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();
    }

  }
}

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

不幸的是,无法捕获StackOverflowException

见:

。。。 从.NET框架开始 版本2.0,StackOverflowException 对象不能被try-catch捕获 块,相应的进程是 默认终止。

更新:

在对我的旧问题进行进一步调查后,我发现了以下旧线索:

自.net framework 2.0以来,无法使用try-catch语句捕获StackOverflowException