The delegate is a function pointer to the function, and is type-safe. One of the useful operations that can be performed using a delegate is to implement callback. Callback is the method used to pass in a function. This method is called when the function is executed. For example, when a function is called to execute a very time-consuming operation, a callback method (implemented by delegation) is also passed in to complete the function execution, call this callback method to notify the user of the calculation result. The following is an example of implementing callback using delegation:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace DelegateDemo{ class Program { delegate void callBackdelegate(string strMessage); static void Main(string[] args) { callBackdelegate callback = ResultCallback; AddNumber(100, 200, callback); Console.ReadLine(); } static void AddNumber(int num1, int num2,callBackdelegate callBack) { int result = num1 + num2; callBack("Result is : "+result.ToString()); } static void ResultCallback(string strMessage) { Console.WriteLine(strMessage); } }}
The preceding example only synchronizes the callback. That is to say, when the AddNumber function is executed (assuming that the function is executed for a long time), the UI thread will be blocked until the execution of the function is completed. This brings a poor user experience. In fact, in daily software development, asynchronous callback is the most used technology, which means that the UI thread will not be blocked when the AddNumber function is executed. The preceding example is rewritten using asynchronous callback:
Using System; using System. collections. generic; using System. linq; using System. text; using System. runtime. remoting. messaging; namespace DelegateDemo {class Program {// declare a delegate. The signature is the same as the AddNumber function delegate int MethodDelegate (int num1, int num2); static void Main (string [] args) {MethodDelegate del = AddNumber; AsyncCallback callback = new AsyncCallback (ResultCallBack); IAsyncResult result = del. beginInvoke (100,200, callback, null); Console. WriteLine ("the UI thread continues to execute .... "); Console. readLine ();} static int AddNumber (int num1, int num2) {// use a thread to simulate a time-consuming operation System. threading. thread. sleep (5000); return num1 + num2;} static void ResultCallBack (IAsyncResult ar) {// to forcibly convert the ar to AsyncResult type, this type must be introduced to the namespace System. runtime. remoting. messaging MethodDelegate del = (MethodDelegate) (AsyncResult) ar ). asyncDelegate; int result = del. endInvoke (ar); Console. writeLine ("The result is:" + result. toString ());}}}
The preceding Code implements asynchronous callback for the AddNumber function.