1. 程式人生 > >C#中委托的同步和異步有什麽區別

C#中委托的同步和異步有什麽區別

null 實現 random ini spa fun 委托 是個 res

通過定義委托,來實現同步和異步,委托通過Action和Func來實現,記錄學習委托的同步和異步的過程


委托的同步方法

委托的Invoke方法用來進行同步調用。

        static void Main(string[] args)
        {
            //無參數方法
            Action action = () => Console.WriteLine("action方法執行");

            action.Invoke();

            //有一個參數(多個參數基本相同)
            Action<string
> action2 = (t) => Console.WriteLine("action方法執行,{0}", t); action2.Invoke("我在測試"); //帶一個參數帶返回值 Func<int, bool> func = (t) => { int i = new Random().Next(1, 10); Console.WriteLine("隨機數是{0}", i); return i > t; }; bool b = func.Invoke(5); Console.WriteLine("{0}",b); Console.Read(); }

同步調用會阻塞線程,如果是要調用一項繁重的工作(如大量IO操作),可能會讓程序停頓很長時間,造成糟糕的用戶體驗,這時候異步調用就很有必要了。


委托的異步調用

異步調用不阻塞線程,而是把調用塞到線程池中,程序主線程或UI線程可以繼續執行。委托的異步調用通過BeginInvoke和EndInvoke來實現。

        static void Main(string[] args)
        {
            //無參數方法
            Action action = () => Console.WriteLine("action方法執行");

            action.BeginInvoke(null,null);

            //有一個參數(多個參數基本相同)
            Action<
string> action2 = (t) => Console.WriteLine("action方法執行,{0}", t); action2.BeginInvoke("我是個測試",null,null); //帶一個參數帶返回值 Func<int, bool> func = (t) => { int i = new Random().Next(1, 10); Console.WriteLine("隨機數是{0}", i); return i > t; }; var result = func.BeginInvoke(5,null,null); bool b = func.EndInvoke(result); Console.WriteLine("{0}",b); Console.Read(); }


異步回調

用回調函數,當調用結束時會自動調用回調函數,解決了為等待調用結果,而讓線程依舊被阻塞的局面。

        static void Main(string[] args)
        {
            //無參數方法
            Action action = () => Console.WriteLine("action方法執行");

            AsyncCallback callback1 = t =>
            {
                Console.WriteLine("我是回調1");
            };

            action.BeginInvoke(callback1, null);

            //有一個參數(多個參數基本相同)
            Action<string> action2 = (t) => Console.WriteLine("action方法執行,{0}", t);
            AsyncCallback callback2 = t =>
            {
                Console.WriteLine("我是回調2");
            };
            action2.BeginInvoke("我是個測試", callback2, null);

            //帶一個參數帶返回值
            Func<int, bool> func = (t) => {

                int i = new Random().Next(1, 10);
                Console.WriteLine("隨機數是{0}", i);
                return i > t;

                };
            AsyncCallback callback3 = t =>
            {
                Console.WriteLine("我是回調3");
            };
            var result = func.BeginInvoke(5, callback3, null);

            bool b = func.EndInvoke(result);

            Console.WriteLine("{0}",b);

            Console.Read();
        }

C#中委托的同步和異步有什麽區別