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

 

posted @ 2017-08-20 16:37  落花流水Zxxxx  阅读(138)  评论(0编辑  收藏  举报