开发者

DispatcherUnhandledException with Class Library called via Reflection

I Load a WPF MVVM Class Library with reflection. I also need an exception Handler as described here.

Since this is a Hosted WPF App, I can't use App.xaml ! It's why I implemented all needed in the class wich Load my application, as explained here, including :

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

The problem here is that when I throw an Exception (from a backgroundworker thread BTW), It doesn't work well. In effect, if I manually throw a NullReferenceException by calling th开发者_如何学Ce Dispatcher.Invoke (in order to throw the exception in the UI thread), and when I get into the Current_DispatcherUnhandledException debugger, the Exception I see is not NullReferenceException, but the helly TargetInvocation Exception with a "Exception has been thrown by the target of an invocation" message.

I figured out that this Exception is maybe thrown by the invoke method, the one which call the WPF dll by reflection.

It looks like the NullReferenceException is caught by the "WPF class library caller method", before the wpf application...

It's making me go crazy !

Please help !


The NullReferenceException is indeed caught by the WPF framework and wrapped in a TargetInvocationException. The original NullReferenceException is still available in the InnerException field of the TargetInvocationException.

Here's an example on how to retrieve the original exception:

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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜