0

I had an old Windows Forms Program which I am trying to convert to WPF but I have an issue where the new program throws a "System.NullReferenceException: Object reference not set to an instance to an object" and I don't know how to resolve it. The "old" code is as following:

            if (InvokeRequired) {
                try {
                   Invoke((MethodInvoker)delegate {
                       PackedReceived((ResponseArgs)Packet);
                    });
                } catch {
                    return;
                }
            } else {
               PackedReceived((ResponseArgs)Packet);
            }
        }

The "InvokeRequired" apparently doesn't work in WPF so I changed the code to:

        {
            if (!Dispatcher.CheckAccess())
            {
                try
                {
                    Dispatcher.Invoke((MethodInvoker)delegate {
                        PackedReceived((ResponseArgs)Packet);
                    });
                }
                catch
                {
                    return;
                }
            }
            else
            {
                PackedReceived((ResponseArgs)Packet);
            }
        }

My new solution doesn't work and throws the exception mentioned above. Does anybody have an idea about this? Thanks in advance.

Clemens
  • 123,504
  • 12
  • 155
  • 268
  • `(MethodInvoker)delegate ...` looks odd, that is a WinForms type. Use `Dispatcher.Invoke(() => PackedReceived((ResponseArgs)Packet))`. And remove the try/catch, it's useless. – Clemens Jul 19 '20 at 08:54
  • Hi, thanks for your answer. I changed the code to: 'if (!Dispatcher.CheckAccess()) { Dispatcher.Invoke(() => PackedReceived((ResponseArgs)Packet)); } else { PackedReceived((ResponseArgs)Packet); }' But I'm still running into the same error. Also I read the "What is a NullReferenceException, and how do I fix it?" and it does explain the error but I don't know how to fix it. Any ideas? – stormbreaker18 Jul 19 '20 at 10:16
  • You should debug you program in order to find out where exactly the exception is thrown. – Clemens Jul 19 '20 at 10:17

0 Answers0