2011-05-27 10 views
1

Iリフレクションを使用してWPF MVVMクラスライブラリをロードします。 hereのように例外ハンドラも必要です。Reflection経由で呼び出されたクラスライブラリのDispatcherUnhandledException

これはHosted WPF Appなので、App.xamlを使用することはできません! それは私がクラスウィッヒに必要なすべてを実装する理由ですhereが説明したように、私のアプリケーションをロードし、含む:

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

ここでの問題は、私は(ところでBackgroundWorkerのスレッドから)例外をスローするとき、それはないということですうまくできた。 実際にDispatcher.Invoke(UIスレッドで例外をスローするために)を呼び出してNullReferenceExceptionをスローすると、Current_DispatcherUnhandledExceptionデバッガに入ると例外が表示されますが、NullReferenceExceptionではなくTargetInvocation 「呼び出しのターゲットによって例外がスローされました」という例外を持つ例外。

私は、この例外が、リフレクションによってWPF dllを呼び出すinvokeメソッドによってスローされる可能性があることを知りました。

それはと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 
} 
:ここ

は、元の例外を取得する方法についての例です
関連する問題