Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does delegate.Invoke work?

If I create a delegate in my code like :

delegate void dostuff (string o);

This generates a class that derives from System.MulticastDelegate which implements three methods - Invoke, BeginInvoke and EndInvoke.

If I look at the compiled IL for Invoke all I see is :

.method public hidebysig newslot virtual 
        instance void  Invoke(string o) runtime managed
{
} // end of method dostuff::Invoke

The method contains no code. Calling it does work - the delegate gets invoked, but I can't see how it does it.

Where does the voodoo that makes calling Invoke actually call the delegate come from?

like image 358
Mongus Pong Avatar asked Jun 17 '11 16:06

Mongus Pong


People also ask

What is invoke delegate?

Invoke(Delegate): Executes the specified delegate on the thread that owns the control's underlying window handle.

Why delegates why not call methods directly?

If you think of delegates as being similar to interface definitions for a specific type of method, you can start to see why delegates exist. They allow clients of our delegates to ignore all the details of their implementations - even their names!

How does delegate work C#?

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.


1 Answers

The voodoo can be found at the end of the signature: runtime managed. Notice that all of your managed classes and methods that you define will be decorated as cli managed.

runtime managed means that the runtime provides pre-optimized implementations of the methods.

like image 141
Ethan Cabiac Avatar answered Oct 25 '22 12:10

Ethan Cabiac