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 .
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.
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.
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!
Invoke(Object, Object[]) Invokes the method or constructor represented by the current instance, using the specified parameters. Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)
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***
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With