BeginInvoke in TinyCLR

In Gadgeteer I used Program.BeginInvoke()
Show an example how to use BeginInvoke correctly in TinyCLR

I tryed Dispatcher from GHIElectronics.TinyCLR.UI.Threading namespace

        private class Operation
        {
            public Operation(Delegate method, object[] args)
            {
                this.method = method;
                this.args = args;
            }
            public Delegate method;
            public object[] args;
        }

        private static DispatcherOperationCallback Operator = new DispatcherOperationCallback(DoOperation);
        private static object DoOperation(object op)
        {
            var operation = (Operation)op;
            try
            {
                operation.method.Method.Invoke(operation.method.Target, operation.args);
            }
            catch
            {
                Debug.WriteLine("Error invoking method \"" + operation.method.Method.DeclaringType + "\" (check arguments to Program.BeginInvoke are correct)");
            }

            return null;
        }

        public static void BeginInvoke(Delegate method, params object[] args)
        {
            if (method != null && Application.Current.Dispatcher != null)
            {
                if (args == null) args = new object[] { };
                Application.Current.Dispatcher.BeginInvoke(Operator, new Operation(method, args));
            }
        }

but sometimes I get an exception on the line
operation.method.Method.Invoke(operation.method.Target, operation.args);
and Visual Studio 2019 crashes.
Besides, I don’t understand why the Dispatcher is only available in the UI

What is the exception text? Do you have breakpoints set on the invoked method?

I get VS crashes during delegate invocation also, but only if I put a breakpoint on the start of the target delegate code. For some reason, breakpoints on the first instructions of a callee will cause VS to crash.

Yes. But my breakpoint not on the start of the target delegate code

If you remove the breakpoint, does vs still crash? I’m just wondering if we’re still seeing this scenario cause the debugger crash.

No.
If I put a breakpoint at the place where BeginInvoke was called

BeginInvoke(new SetDataDelegate(rc_DataReceived), new object[] { cmd_bufer, rcUart });

then continue debugging step by step, then I get VS crash and restart

Yup - that’s the same behavior I see. This seems to be a bug in the debugger framework (and also in VS itself, which is not supposed to crash, no matter what third-party extensions do). There’s no workaround that I know of other than to break elsewhere or use Debug.WriteLine to do your debugging. This will have to be fixed either in the firmware or the PC-side TinyCLR debugging support dll.

I’ll also try to get an internal issue reported on the VS crash. Even if TinyCLR extensions fail in some way, VS should not exit.