3

This question may sound trivial, but let me ask it nevertheless.

I found on the Internet the following example of calling an anonymous method using Invoke in VB.NET:

Invoke(New MethodInvoker(Sub() SomeMethod(param1)))

But why not call it this way, which looks cleaner? Is there any difference?

Invoke(Sub() SomeMethod(param1))
Mariusz Schimke
  • 3,185
  • 8
  • 45
  • 63
  • possible duplicate of [MethodInvoker vs Action for Control.BeginInvoke](http://stackoverflow.com/questions/1167771/methodinvoker-vs-action-for-control-begininvoke) – sloth Feb 13 '14 at 10:25
  • No, I don't think so. My question is more about why to instantiate a MethodInvoker. Both pieces of code I presented in my question compile correctly and work correctly. So the MethodInvoker instantiation seems redundant. I just want to make sure if I'm right. – Mariusz Schimke Feb 13 '14 at 11:40
  • 1
    The only difference is that in your first example, you create an extra delegate of type `MethodInvoker`, which is simple a `void` method without parameters. `Invoke` does not care if it is called with a `MethodInvoker` instance or any other delegate type that is similiar to it. The documentation mentions that using a `MethodInvoker` should be faster, but I don't think that there's a difference significant enough to care about in most cases. I would stick with the second example, because it is more readable IMHO. – sloth Feb 13 '14 at 12:13
  • You are right about the speed. It's unbelievable, but the first example is more than 3 times faster than the second one. I've just performed a simple test calling the example pieces of code a million times in a loop. – Mariusz Schimke Feb 13 '14 at 12:39
  • 1
    One explanation would be, that the compiler does not cast the second one to a `MethodInvoker` delegate since `Invoke` *accepts* `Delegate` as parameter. And since when using anonymous procedures `Invoke` **requires** a `MethodInvoker` the cast will be done at Runtime which may well impact the performance. – MrPaulch Feb 13 '14 at 14:15

1 Answers1

1

Just to conclude and close the topic. Based on the comments, both the examples of Invoke calls are correct, but the one using MethodInvoker instantiation is faster, because no extra typecasting has to be performed at runtime, as MrPaulch stated.

Mariusz Schimke
  • 3,185
  • 8
  • 45
  • 63