Delegate is often used to compare with callbacks, in fact, in fact, to some extent, a lot of common. But delegate has a lot of more powerful places.
First, you can register any multiple callbacks in Delegate. When a delegate is called, the registered process will be called one by one.
Second, Delegate allows you to register a method of objects, not like C , you can use a static method or global method as a function pointer, but also imply that we have saved the Object in some way in delegate. information.
In an anonymous delegate in C # 2.0, we can even access the context variable currently anonymous. In the next article, we will take a powerful delegate through the actual example.
First, let's take a look at a typical delegate in C # 1.2.
Public Delegate Void Theevent (INT A); PUBLIC VOID TEST () {Theevent TestDel1 = New Theevent (DEL1); TestDel1 (12);} public void del1 (int x) {console.writeline ("Output x: {0}" , X);
Now we can write this:
Public void test () {theevent testdel1 = DEL1; TESTDEL1 (12);}
Or turn the program to:
Delegate void theeent2 (int A); public void test2 () {int a = 12; theevent ev2 = delegate (Ref INT X) {Console.WriteLine ("Output x: {0}", x);}; ev2 (Ref a);
Compared with 1.2, Delegate is more readable, but does not seem to have essential improvement? Slow, let's take a look at the example below.
Public static void test3 () {int a = 12; int y = 32; theevent ev2 = delegate (ref int x) {console.writeline ("Output X Y: {0}", X Y);}; EV2 (ref A);
Note that the content in the anonymous function! The value of X Y is the correct output, and in 1.2, the delegate to local variables is not accessible outside the parameters. What is the benefit of doing this?
Let us look at a more complex example:
Public static void test4 () {INT A = 12; int y = 32; theevent ev2 = delegate (ref int x) {console.writeLine ("Output X Y: {0}", X Y); thread.sleep (100);}; // EV2 (REF A); IASYNCRESULT AR = Ev2.BeginInvoke (REF A, DELEGATE (IASYNCRESULT AR2) {Console.write ("Operation Finished: {0} on thread ID: {1}, IS pool: {2} ", ar2.IsCompleted, Thread.CurrentThread.GetHashCode (), Thread.CurrentThread.IsThreadPoolThread);}, null); Console.WriteLine (" do some other calculations while counter thread is working "); Console. Write ( "work status: {0} Main Thread ID: {1}, is pool: {2}", ar.IsCompleted, Thread.CurrentThread.GetHashCode (), Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep (500) Ev2.endinvoke (REF A, AR);} This example uses the system thread pool to queuigate the task, suitable for IO or calculate intensive operations. Using anonymous entrustment is the most beneficial to completely clonally cloning the available variables of the current running space, although this may also increase the complexity of synchronization from the other level, the so-called failed.