码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2019-03-08 23:31:04      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:handler   其他   hand   OLE   syn   null   and   handle   子线程   

    public delegate int AddHandler(int a, int b);
    public class JiaFa
    {
        public static int Add(int a, int b)
        {
            Console.WriteLine("开始计算:" + a + "+" + b);
            Thread.Sleep(3000);
            Console.WriteLine("计算完成");
            return a + b;
        }
    }

同步调用

        static void Main1(string[] args)
        {
            //方式1
            AddHandler handler = new AddHandler(JiaFa.Add);
            var res = handler.Invoke(3, 5);
            Console.WriteLine("继续做其他事情");
            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 Main2(string[] args)
        {
            AddHandler handler = new AddHandler(JiaFa.Add);
            IAsyncResult result = handler.BeginInvoke(3, 5, null, null);
            Console.WriteLine("继续做其他事情1");
            //当主线程执行到EndInvoke时,如子线程还没有执行完,则主线程还是需要等待
            Console.WriteLine(handler.EndInvoke(result));
            Console.WriteLine("继续做其他事情2");
            Console.ReadKey();
        }

异步回调

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

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

标签:handler   其他   hand   OLE   syn   null   and   handle   子线程   

原文地址:https://www.cnblogs.com/yinchh/p/10498770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!