简体   繁体   中英

WPF Dispatcher throws TargetInvocationException

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";
        }));            

    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM