2011-05-27 45 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 
}