Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference is there Invoke Method (Delegate) and direct call? [duplicate]

Tags:

c#

May be this question asked earlier ,i did googling but i didnt get answer.

Delegate Prototype

delegate void method1(string str); 

Adding Callback methods

method1 objDel2;            objDel2 = new method1(TestMethod1);             objDel2("test"); objDel2.Invoke("Invoke"); 

In Above coding objDel2("test"); and objDel2.Invoke("Invoke"); are doing same task.Which one is good or both are same .

like image 590
Prabhakaran Parthipan Avatar asked Aug 28 '13 12:08

Prabhakaran Parthipan


People also ask

What is the difference between Invoke and BeginInvoke method in C#?

Invoke : Executes on the UI thread, but calling thread waits for completion before continuing. Control. BeginInvoke : Executes on the UI thread, and calling thread doesn't wait for completion.

What is invoke delegate?

Invoke(Delegate) Executes the specified delegate on the thread that owns the control's underlying window handle. Invoke(Delegate, Object[]) Executes the specified delegate, on the thread that owns the control's underlying window handle, with the specified list of arguments.

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!

What is invoke method in C#?

Invoke(Object, Object[]) Invokes the method or constructor represented by the current instance, using the specified parameters. Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)


1 Answers

They are 100% identical - this is pure compiler sugar (see below). As for which is preferred: neither / both.

static class Program {      static void Main()     {         method1 objDel2;         objDel2 = new method1(TestMethod1);         objDel2("test");         objDel2.Invoke("Invoke");     }     delegate void method1(string val);     static void TestMethod1(string val) {         System.Console.WriteLine(val);     } } 

has the IL

.method private hidebysig static void Main() cil managed {     .entrypoint     .maxstack 2     .locals init (         [0] class Program/method1 'method')     L_0000: ldnull      L_0001: ldftn void Program::TestMethod1(string)     L_0007: newobj instance void Program/method1::.ctor(object, native int)     L_000c: stloc.0      L_000d: ldloc.0      L_000e: ldstr "test"     L_0013: callvirt instance void Program/method1::Invoke(string) ***HERE***     L_0018: ldloc.0      L_0019: ldstr "Invoke"     L_001e: callvirt instance void Program/method1::Invoke(string) ***HERE***     L_0023: ret  } 

Note both do the same thing (see the two locations marked by me as ***HERE***)

like image 155
Marc Gravell Avatar answered Sep 21 '22 06:09

Marc Gravell