C# 委託隨筆

來源:互聯網
上載者:User

       委託是指向函數的函數指標,而且是型別安全的。使用委託可以執行的一項有用操作是實現回調。回調是傳入函數的方法,在函數結束執行時調用該方法。例如,有一個函數執行一個非常耗時的操作,在調用該函數時,同時也傳入了一個回調方法(利用委託實現),從而在函數執行完成時,調用該回調方法,通知使用者計算的結果。下面是一個用委託實現回調的樣本:

     

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);        }    }}

  上面的樣本只是同步回調,也就是說在執行函數AddNumber時(假設該函數執行很長時間),UI線程是會阻塞的,至到該函數執行完畢。這就給使用者帶來了不好的體驗。其實我們在日常的軟體開發中,用的最多的就是非同步回調技術,該技術是指 在執行函數AddNumber時,UI線程不會阻塞。下面我們就用非同步回調重寫上面的樣本:

     

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.Remoting.Messaging;namespace DelegateDemo{    class Program    {        //聲明一個委託,簽名與AddNumber函數相同        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("UI線程繼續執行。。。。");            Console.ReadLine();        }        static int AddNumber(int num1, int num2)        {            //用線程類比一個耗時的操作            System.Threading.Thread.Sleep(5000);            return num1 + num2;        }        static void ResultCallBack(IAsyncResult ar)        {            //將ar強制轉換為 AsyncResult 類型 該類型需引入命名空間System.Runtime.Remoting.Messaging            MethodDelegate del = (MethodDelegate)((AsyncResult)ar).AsyncDelegate;            int result = del.EndInvoke(ar);            Console.WriteLine("The result is :" + result.ToString());        }    }}

   以上代碼實現了對函數AddNumber的非同步回調。

    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.