views:

71

answers:

1

Currently I useDynamicInvokewhich is very slow. Still using theDelegatetype how can I directly invoke the Delegate without late-binding/theDynamicInvoke?

Delegate _method;    
_method.DynamicInvoke(_args);

Thanks.

+1  A: 

Invoke is faster, but it's a bit "hidden". From MSDN on Delegate class

The common language runtime provides an Invoke method for each delegate type, with the same signature as the delegate. You do not have to call this method explicitly from C#, Visual Basic, or Visual C++, because the compilers call it automatically. The Invoke method is useful in reflection when you want to find the signature of the delegate type.

What this means is that when you create a delegate type, the Invoke member is added with the correct signature by the compiler. This allows calling without going through DynamicInvoke

In c#, you use this like:

_method(_args);
//or
_method(typedArg1, typedArg2, andSoOn);

calling it as you would a normal method. This actually calls Invoke, which should be much faster for you.

Philip Rieck
Hrmmm I can't change the code to _method(_args);. I get a compiler error 'Method, delegate or event is expected'
DayTwo
Is your delegate actually just a "Delegate"? or are you using a declared signature for it?
Philip Rieck
It's a System.Delegate. Thanks
DayTwo
Ahh, sorry - Then that makes sense. If you are using only `System.Delegate` as the delegate type, then no `Invoke` method will be generated. If you can create a specific delegate, you will see huge speed improvements. However, with just a `Delegate`, this is not possible - every invocation will be a dynamic one. I would suggest looking at c# 4 and the `dynamic` type if you really need to go this route as the DLR has some speed improvements.
Philip Rieck