wpf - 通过反射调用带有类库的DispatcherUnhandledException

标签 wpf mvvm unhandled-exception targetinvocationexception

我通过反射加载WPF MVVM类库。
我还需要一个异常处理程序,如here所述。

由于这是一个托管WPF应用程序,因此我无法使用App.xaml!
这就是为什么我在加载我的应用程序的类中实现了所需的全部功能,如here所述,包括:

Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(Current_DispatcherUnhandledException);

这里的问题是,当我抛出异常(从backgroundworker线程BTW)时,它不能很好地工作。
实际上,如果我通过调用Dispatcher.Invoke手动引发NullReferenceException(以便在UI线程中引发异常),并且当我进入Current_DispatcherUnhandledException调试器时,我看到的异常不是NullReferenceException,而是令人讨厌的TargetInvocation异常消息“调用的目标已引发异常”。

我发现此异常可能是由invoke方法引发的,该方法通过反射调用WPF dll。

看起来在WPF应用程序之前,“WPF类库调用方法”已捕获NullReferenceException。

这让我发疯了!

请帮忙 !

最佳答案

NullReferenceException确实由WPF框架捕获,并包装在TargetInvocationException中。原始NullReferenceException在TargetInvocationException的InnerException字段中仍然可用。

这是有关如何检索原始异常的示例:

public static void Main()
{
    Dispatcher mainThreadDispatcher = Dispatcher.CurrentDispatcher;

    mainThreadDispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(mainThreadDispatcher_UnhandledException);

    // Setup a thread that throws an exception on the main thread dispatcher.
    Thread t = new Thread(() =>
        {
            mainThreadDispatcher.Invoke(new Action(
                () =>
                {
                    throw new NullReferenceException();
                }));
        });

    t.Start();

    // Start the dispatcher on the main thread.
    Dispatcher.Run();
}

private static void mainThreadDispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
    Exception targetInvocationException = e.Exception; // e.Exception is a TargetInvocationException
    Exception nullReferenceException = e.Exception.InnerException; // e.Exception.InnerException is the NullReferenceException thrown in the Invoke above
}

关于wpf - 通过反射调用带有类库的DispatcherUnhandledException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6149905/

相关文章:

c++ - 进程外使用MiniDumpWriteDump时如何获取异常信息?

c# - NLog:强制 BufferingTargetWrapper 在 AppDomain UnhandledException 上清空

c++未处理的异常 - 如何调试

c# - 我怎么知道我的所有模块是否都已加载到 prism 4 中?

c# - 如何使用包装面板处理选择事件

xamarin - 在不使用现有MVVM框架的情况下使用MVVM模式进行页面导航

wpf - MVVM 窗口/区域处理

c# - 通过代码将 Eventhandler 添加到 DataTemplate 内的形状

c# - WPF 文本框绑定(bind)在使用字符串格式时不起作用

c# - Kinect SDK 1.7 |更改 KinectCursor 图像和大小