0

I'm confused with using and not using Invoke.

In the following example, I see no difference with

int answer = b(10, 10);

and

int answer = b.Invoke(10, 10);

so can anyone help me with this? thx!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TEST
{
    public delegate int BinaryOp(int x, int y);
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main innvoked on thread {0}.", Thread.CurrentThread.ManagedThreadId);
            BinaryOp b = new BinaryOp(add);
            //int answer = b(10, 10);      
            int answer = b.Invoke(10, 10); 

            Console.WriteLine("Doing more work in Main");
            Console.WriteLine("10 + 10 is {0}", answer);
            Console.Read();
        }

        static int add(int x, int y)
        {
            Console.WriteLine("add innvoked on thread {0}.", Thread.CurrentThread.ManagedThreadId);
            return x + y;
        }
    }
}
Ken White
  • 123,280
  • 14
  • 225
  • 444
David4866
  • 43
  • 7

1 Answers1

0

Basically there is no difference.

Specifically since a Delegate is not really a function rather a holder to a function, that class that holds the function has to have some way to Invoke it. Hence the method Invoke. On the other hand the compiler is smart enough to automatically call Invoke when you append parenthesis to a Delegate. See https://jacksondunstan.com/articles/3283.

MotKohn
  • 3,485
  • 1
  • 24
  • 41