• 同步、异步、异步回调


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Runtime.Remoting.Messaging;
    
    namespace Async
    {
        public delegate int AddHandler(int a, int b);
    
        public class AddCls
        {
            public static int Add(int a, int b)
            {
                Console.WriteLine("开始计算:" + a + "+" + b);
                Thread.Sleep(3000);
                Console.WriteLine("计算完成!");
                return a + b;
            }
        }
    
        public class Test
        {
            static void Main(string[] args)
            {
                //同步
                //sync();
    
                //异步
                //async();
    
                //异步回调
                asyncCallBack();
    
            }
    
            /// <summary>
            /// 同步
            /// </summary>
            private static void sync()
            {
                Console.WriteLine("===== 同步调用 SyncInvokeTest =====");
                AddHandler handler = new AddHandler(AddCls.Add);
                int result = handler.Invoke(1, 2);
                Console.WriteLine("继续做别的事情。。。");
                Console.WriteLine("和等于:" + result);
                Console.ReadKey();
            }
    
            /// <summary>
            /// 异步
            /// </summary>
            private static void async()
            {
                Console.WriteLine("===== 异步调用 AsyncInvokeTest =====");
                AddHandler handler = new AddHandler(AddCls.Add);
                IAsyncResult ir = handler.BeginInvoke(1, 2, null, null);
                Console.WriteLine("继续做别的事情。。。");
                int result = handler.EndInvoke(ir);
                Console.WriteLine("和等于:" + result);
                Console.ReadKey();
            }
    
            /// <summary>
            /// 异步回调
            /// </summary>
            private static void asyncCallBack()
            {
                Console.WriteLine("===== 异步调用 AsyncInvokeTest =====");
                AddHandler handler = new AddHandler(AddCls.Add);
                IAsyncResult ir = handler.BeginInvoke(1, 2, new AsyncCallback(callBack), "AsycState:OK");
                Console.WriteLine("继续做别的事情。。。");
                Console.ReadKey();
            }
    
            /// <summary>
            /// 回调
            /// </summary>
            private static void callBack(IAsyncResult ir)
            {
                AddHandler handler = (AddHandler)((AsyncResult)ir).AsyncDelegate;
                Console.WriteLine(handler.EndInvoke(ir));
                Console.WriteLine(ir.AsyncState);
            }
        }
    }
  • 相关阅读:
    进程控制(二)
    进程控制(一)
    python的signal
    python的logging模块
    python守护进程
    C语言关键字、标识符和注释
    青春代码
    冒泡排序 js
    数组
    js 运算符
  • 原文地址:https://www.cnblogs.com/valor-xh/p/5940604.html
Copyright © 2020-2023  润新知