2

I have a problem with my debugger, when faulty code is executed in the UI Thread the debugger correctly points out the faulty line, same when this is executed inside a thread, but it behaves kind of weird when called inside a dispatcher : TargetInvocationException is thrown in the disassembly.

How could I have it displayed properly and avoid this annoying message?

Here is a simple example that illustrates the problem:

private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        //navigator.NavigatToMenuAccueil(true);

        //Throws NullPointerException
        /*String x = null;
        String y = x.ToUpper();*/

        Thread th = new Thread(DoWork);
        th.Start();
    }

    private void DoWork()
    {
        //Throws NullPointerException
        /*String x = null;
        String y = x.ToUpper();*/

        Thread.Sleep(1000);
        Dispatcher.BeginInvoke(new Action(() =>
        {
            //Throws TargetInnvocationException 
            /*
            String x = null;
            String y = x.ToUpper();
             */

            MyTextBlock.Text = "My New Text";
        }));            

    }
jeN
  • 23
  • 1
  • 3

1 Answers1

2

TargetInvocationException is the exception that is thrown by methods invoked by reflection (according to MSDN), and by using BeginInvoke, you are telling the Dispatcher to do that.

Any exception that is thrown inside the passed delegate is wrapped in a TargetInvocationException. You can't prevent the Dispatcher from wrapping the original exeption. You can still get at the original exception by accessing InnerException though.

Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • Thanks for the explanation, is there a workaround? another way to modify a UI element from a thread and still having the debugger work properly? – jeN Mar 14 '13 at 14:05
  • @jeN The debugger still works properly, you just have to expand the InnerException property on the TargetInvocationException. If you catch the exception, you can do anything you want with the InnerException, which is what you're after. But rethrowing the InnerException would erase its StackTrace, which is probably not what you want. – Botz3000 Mar 14 '13 at 14:13
  • What I meant by the "dubugger not properly working", is that I can't see the original exception in the call stack, I can't see the values of the variables, the exception is absorbed by the targetinvocationexception. Will I have this kind of problems if I use AsyncTask Istead? – jeN Mar 14 '13 at 14:29
  • @jeN Using VS2012, your example breaks with the correct exception. Maybe your version of VS handles it differently? However, you could try catching the exception inside your Lambda and then set a breakpoint there. – Botz3000 Mar 15 '13 at 07:28