C # Delegation

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.