C#--委託的同步,異步,回調函數

原文地址異步

同步調用

委託的Invoke方法用來進行同步調用。同步調用也能夠叫阻塞調用,它將阻塞當前線程,而後執行調用,調用完畢後再繼續向下進行。函數

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace invoke
{
    public delegate int AddHandler(int a, int b);
    public class 加法類
    {
        public static int Add(int a, int b)
        {
            Console.WriteLine("開始計算:" + a + "+" + b);
            Thread.Sleep(3000); //模擬該方法運行三秒
            Console.WriteLine("計算完成!");
            return a + b;
        }
    }

    public class 同步調用
    {
        static void Main()
        {
            Console.WriteLine("===== 同步調用 SyncInvokeTest =====");
            AddHandler handler = new AddHandler(加法類.Add);
            int result = handler.Invoke(1, 2);

            Console.WriteLine("繼續作別的事情。。。");
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

異步調用

異步調用不阻塞線程,而是把調用塞到線程池中,程序主線程或UI線程能夠繼續執行。委託的異步調用經過BeginInvoke和EndInvoke來實現。spa

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace invoke
{

    public class 異步調用
    {
        static void Main2()
        {
            Console.WriteLine("===== 異步調用 AsyncInvokeTest =====");
            AddHandler handler = new AddHandler(加法類.Add);
            //IAsyncResult: 異步操做接口(interface)
            //BeginInvoke: 委託(delegate)的一個異步方法的開始
            IAsyncResult result = handler.BeginInvoke(1, 2, null, null);
            Console.WriteLine("繼續作別的事情。。。");
            //異步操做返回
            Console.WriteLine(handler.EndInvoke(result));
            Console.ReadKey();
        }
    }
}

異步回調

用回調函數,當調用結束時會自動調用回調函數,能夠在回調函數裏觸發EndInvoke,這樣就能夠避免程序一直佔用一個線程,就釋放掉了線程.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace invoke
{
    public class 異步回調
    {
        static void Main3()
        {
            Console.WriteLine("===== 異步回調 AsyncInvokeTest =====");
            AddHandler handler = new AddHandler(加法類.Add);
            //異步操做接口(注意BeginInvoke方法的不一樣!)
            IAsyncResult result = handler.BeginInvoke(1, 2, new AsyncCallback(回調函數), "AsycState:OK,這裏輸出的是AsyncState的參數內容");
            Console.WriteLine("繼續作別的事情。。。");
            Console.ReadKey();
        }
        static void 回調函數(IAsyncResult result)
        {
            //result 是「加法類.Add()方法」的返回值
            //AsyncResult 是IAsyncResult接口的一個實現類,引用空間:System.Runtime.Remoting.Messaging
            //AsyncDelegate 屬性能夠強制轉換爲用戶定義的委託的實際類。
            AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
            Console.WriteLine(handler.EndInvoke(result));
            Console.WriteLine(result.AsyncState);
        }
    }
}

代碼下載線程

相關文章
相關標籤/搜索