我通过反射加载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/