代码之家  ›  专栏  ›  技术社区  ›  configurator

捕获StackOverflowException

  •  6
  • configurator  · 技术社区  · 15 年前

    我怎样才能抓住 StackOverflowException ?

    我有一个允许用户编写脚本的程序,当运行任意用户代码时,我可能会得到一个 栈溢出异常 try - catch

    this 是我能找到的信息最丰富的答案,但仍然把我引向了死胡同;从 article in the BCL team's blog 我发现我应该用 RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup PrePrepareMethodAttribute

    我也尝试过使用AppDomain并处理 UnhandledException 以及 DomainUnload 事件-但整个进程在堆栈溢出时被终止。即使我 throw new StackOverflowException(); 手动操作,而不会得到实际的堆栈溢出。

    4 回复  |  直到 9 年前
        1
  •  2
  •   David Culp    15 年前

    要处理代码未处理的异常,可以订阅AppDomains UnhandledException——当操作系统显示程序意外退出的对话框时,它将处理该异常。

    在你的程序使用的主要方法

    无功电流域=AppDomain.CurrentDomain公司;

    然后向事件添加处理程序

    在处理程序中,您可以执行任何操作,例如记录、显示错误,甚至根据需要重新初始化程序。

        2
  •  2
  •   Lunatic Experimentalist    15 年前

        3
  •  0
  •   SLaks    15 年前

    您需要在单独的进程中运行代码。

        4
  •  0
  •   Pierre-Alain Vigeant    15 年前

    你必须创建一个不同的 AppDomain 因为您无法从加载的域卸载程序集,并且您不希望关闭主应用程序域。

    var scriptDomain = AppDomain.CreateDomain("User Scripts");
    

    然后可以从需要创建的程序集中加载任何类型。必须确保要加载的对象继承自 MarshalByRefObject .

    我假设您的用户脚本被包装在这样定义的对象中:

    public abstract UserScriptBase : MarshaByRefObject
    {
        public abstract void Execute();
    }
    

    因此,您可以像这样加载任何用户脚本:

    object script = domain.CreateInstanceFromAndUnwrap(type.Location, type.FullName);
    

    scriptDomain.UnhandledException 并监视任何不可恢复的错误。

    我建议你 some tutorial 你可以在网上找到。