简体   繁体   中英

How do I invoke a Delegate faster than by using DynamicInvoke?

Currently I use DynamicInvoke which is very slow. Still using the Delegate type how can I directly invoke the Delegate without late-binding/the DynamicInvoke ?

Delegate _method;    
_method.DynamicInvoke(_args);

Thanks.

The open source framework Impromptu-Inteface adds an extension method to Delegate called FastDynamicInvoke that runs a little over 20 times faster than DynamicInvoke by using the DLR instead of reflection.

using ImpromptuInterface

...

_method.FastDynamicInvoke(_args);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM