C# 同步调用、异步调用、异步回调

时间:2022-08-27 13:49:48
    public delegate int AddHandler(int a, int b);
    public class JiaFa
    {
        public static int Add(int a, int b)
        {
            Console.WriteLine(DateTime.Now + " 开始计算:" + a + "+" + b);
            Thread.Sleep(3000);
            Console.WriteLine(DateTime.Now + " 计算完成");
            return a + b;
        }
    }

同步调用

        static void Main1(string[] args)
        {
            //方式1
            AddHandler handler = new AddHandler(JiaFa.Add);
            var res = handler.Invoke(3, 5);
            Console.WriteLine(DateTime.Now + " 继续做其他事情");
            Console.WriteLine(res);
            //方式2
            //AddHandler handler2 = new AddHandler((int a, int b) =>
            //{
            //    Console.WriteLine("开始计算:" + a + "+" + b);
            //    Thread.Sleep(3000);
            //    Console.WriteLine("计算完成");
            //    return a + b;
            //});
            //Console.WriteLine(handler2(3, 5));
            Console.ReadKey();
        }

异步调用

        static void Main(string[] args)
        {

            AddHandler handler = new AddHandler(JiaFa.Add);
            IAsyncResult result = handler.BeginInvoke(3, 5, null, null);
            Thread.Sleep(1000);
            Console.WriteLine(DateTime.Now + " 继续做其他事情1");
            //当主线程执行到EndInvoke时,如子线程还没有执行完,则主线程还是需要等待
            Console.WriteLine(handler.EndInvoke(result));
            Console.WriteLine(DateTime.Now + " 继续做其他事情2");
            Console.ReadKey();
        }

异步回调

        static void Main3(string[] args)
        {
            AddHandler handler = new AddHandler(JiaFa.Add);
            Console.WriteLine(DateTime.Now + " 继续做其他事情1");
            IAsyncResult result = handler.BeginInvoke(3, 5, new AsyncCallback(Call), "AsycState:OK");
            Console.WriteLine(DateTime.Now + " 继续做其他事情2");
            Console.ReadKey();
        }
        static void Call(IAsyncResult result)
        {
            AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
            Console.WriteLine(handler.EndInvoke(result));
            Console.WriteLine(result.AsyncState);
        }