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);
            }
    
  • 相关阅读:
    检索COM类工厂中CLSID为{00024500-0000-0000-C000-000000000046}的组件时失败
    VSTO 开发中 应用ActionPane、CustomTaskPane
    Thread.Join()的详解
    HBase笔记
    Hive命令详解
    视频地址
    几种表
    如何将数据导入到hive中
    hdfs笔记
    分区表简介
  • 原文地址:https://www.cnblogs.com/yinchh/p/10498770.html
Copyright © 2011-2022 走看看