2011-05-27 93 views
1

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

由于这是一个托管的WPF应用程序,我不能使用App.xaml! 这就是为什么我实现了所有需要的类至极载入我的应用程序,如解释here,包括:

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

这里的问题是,当我抛出一个异常(从一个BackgroundWorker线程BTW),它不工作得很好。 实际上,如果我通过调用Dispatcher.Invoke(以便在UI线程中抛出异常)手动抛出NullReferenceException,并且当我进入Current_DispatcherUnhandledException调试器时,我看到的异常不是NullReferenceException,而是helly TargetInvocation “调用目标引发异常”消息的例外情况。

我发现这个异常可能是由invoke方法抛出的,它是通过反射调用WPF dll的方法。

它看起来像的NullReferenceException由“WPF类库调用程序法”中招, WPF应用程序...

它让我发疯!

请帮忙!

回答

2

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 
}