Search code examples
c#delegatesmethod-invocation

Difference between this two uses of MethodInvoker


What exactly is the difference between this two uses of MethodInvoker:

1:

textBox1.Invoke(new MethodInvoker(b));

2:

textBox1.Invoke((MethodInvoker)delegate { b(); });

I only understand, that variant 2 allow me to call b() with parameters if i want. But what is the difference between this 2 versions?

Version 1 is clear to me: I create a new delegate and pass it my b() method, which has the same return-type and paramaters as the MethodInvoker delegate. Standardcase of a delegate.

But what does version 2 exactly? What means/does here the "delegate" keyword?


Solution

  • V1 creates a new MethodInvoker object and passes it your b method as a parameter. What the MethodInvoker then "does with b" is up the the class itself.

    In V2 you create a anonymous method and cast it to MethodInvoker and do not instanciate any "additional object" and your delegate is executed "directly". Another even shorter way of calling this using Lambdas:

    textBox1.Invoke(() => b()); // or .Invoke((Action)() => b());
    

    In V1 you could also replace MethodInvoker with your own implementation, e.g. a TryCatchLogInvoker which does not execute b directly, but wraps it to logs exceptions happening "inside b".