zoukankan      html  css  js  c++  java
  • C# 同步调用、异步调用、异步回调

        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);
            }
    
  • 相关阅读:
    oracel中wm_concat函数使用
    plsql快捷键设置
    mybatis generator--逆向工程工具的使用
    subline_2使用格式化html等文件
    subline的使用
    关于ssm整合过程中,spring配置文件无提示功能
    初识shell脚本
    ReentrantReadWriteLock原理
    策略模式
    适配器模式
  • 原文地址:https://www.cnblogs.com/yinchh/p/10498770.html
Copyright © 2011-2022 走看看