C#委托調用(同步調用,異步調用,異步回調)


 

     #region 委托回調
        static void delegateTest()
        {
            Console.WriteLine("同步調用");
            SubDelegate subDel = Sub;
            var result = subDel.Invoke(3, 4);
            Console.WriteLine("繼續");
            Console.WriteLine(result);
            Console.ReadKey();

            Console.WriteLine("異步調用");
            SubDelegate sub1 = new SubDelegate(Sub);
            IAsyncResult result1 = sub1.BeginInvoke(2, 3, null, null);
            Console.WriteLine("Go on");
            Console.WriteLine(sub1.EndInvoke(result1));
            Console.ReadKey();

            Console.WriteLine("異步回調");
            SubDelegate sub2 = new SubDelegate(Sub);
            IAsyncResult result2 = sub2.BeginInvoke(5, 6, new AsyncCallback(CallBack), null);
            Console.WriteLine("Go on");
            Console.ReadKey();
        }
        delegate int SubDelegate(int a, int b);
        static int Sub(int a, int b)
        {
            Console.WriteLine("開始計算");
            Thread.Sleep(3000);
            Console.WriteLine("結算完成");
            return a - b;
        }
        static void CallBack(IAsyncResult result)
        {
            SubDelegate sub = (SubDelegate)((AsyncResult)result).AsyncDelegate;
            Console.WriteLine(sub.EndInvoke(result));
        }
        #endregion

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com