c# - AppDomain 未处理的异常

标签 c# exception-handling appdomain

有很多主题涵盖了这个问题。但是我有一个问题。

我像这样将程序集加载到新的 AppDomain 中:

public void Run()
{
    //There's the problem.
    //As Panos Rontogiannis mentioned the thread is created in default AppDomain
    new Thread(RunApp).Start();
}

private void RunApp()
    try
    {
        AppDomain.CreateDomain("domain name").ExecuteAssembly("path to assembly");
    }
    catch (Exception _e)
    {
        MessageBox.Show("Unhandled Exception.\n" + _e);
    }
}

在加载程序集的 Main 方法中,我将我的处理程序订阅到 UnhandledException 事件:

AppDomain.CurrentDomain.UnhandledException += handleException;

处理程序本身:

public static void handleException(object a_s, UnhandledExceptionEventArgs a_args)
{
    var _e = (Exception)a_args.ExceptionObject;
    //Static loger class method
    Loger.WriteError(_e.GetType().ToString(), _e.Message, "default solution");
}

但是无论在加载的程序集中抛出异常,处理程序都不会参与。我只在默认的 AppDomain 中捕获异常(第一个 try{} catch{})。

最佳答案

最有可能的是,您无法在新的 AppDomain 中处理异常的原因是它不是从在该 AppDomain 中创建的线程中抛出的。来自 AppDomain.UnhandledException 上的文档看到这一点并不是很直接。有趣的部分如下:

An exception is unhandled only if the entire stack for the thread has been unwound without finding an applicable exception handler, so the first place the event can be raised is in the application domain where the thread originated.

现在,如果执行抛出代码的线程是在您的主 AppDomain 中创建的(就像控制台应用程序的主线程),那么您应该在主 中添加一个处理程序应用域。请注意,如果抛出的异常类型未加载到主 AppDomain 中,.NET 的程序集加载器将尝试从应用程序的基本目录和探测路径加载它。如果这些与子 AppDomain 不相同,则程序集将不会被解析并抛出(其他)异常。

关于c# - AppDomain 未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15569295/

相关文章:

c# - 为什么 2048x2048 与 2047x2047 数组乘法相比性能会受到巨大影响?

c# - 未呈现后台工作窗口控件

hibernate - Quartz 作业因 StaleObjectStateException 异常而停止执行

PHP : Error: Wrong parameters for Exception with thrown Array Exception

c# - 解析看似正确的日期时间时抛出异常

c# - 在 asp.net mvc 中保存下拉列表中的选定项目

php - 如何从php中的方法显示验证错误

.net - 如何在两个 .NET AppDomain 之间传递未知类型?

.net - 可以防止子 AppDomains 中未处理的异常使主进程崩溃吗?

c# - 将当前程序集加载到不同的AppDomain中