zoukankan      html  css  js  c++  java
  • 常用异步延迟方法

        /// <summary>
        /// 定义与方法同签名的事件委托
        /// </summary>
        public delegate void AsyncEventHandler();
     
        /// <summary>
        /// 定义与方法同签名的回调方法委托
        /// </summary>
        /// <param name="ex">异常信息对象</param>
        public delegate void AsyncCallbackHandler(Exception ex);
     
        /// <summary>
        /// 异步调用引擎类
        /// </summary>
        public class AsyncCallEngine
        {
            /// <summary>
            /// 执行异步方法调用
            /// </summary>
            /// <param name="asyncMethod">异步执行的方法</param>
            /// <param name="callbackMethod">异步执行的方法执行后回调的方法</param>
            public static void Process(AsyncEventHandler asyncMethod, AsyncCallbackHandler callbackMethod)
            {
                try
                {
                    //实例化委托并初赋值
                    AsyncEventHandler acd = new AsyncEventHandler(asyncMethod);
     
                    //实例化回调方法并订阅
                    AsyncCallback acb = new AsyncCallback((ar) =>
                    {
                        //从异步状态ar.AsyncState中,获取委托对象
                        acd = (AsyncEventHandler)ar.AsyncState;
                        Exception _ex = null;
     
                        try
                        {
                            //异步完成,执行回调方法
                            acd.EndInvoke(ar);
                        }
                        catch (Exception ex)
                        {
                            _ex = ex;
                        }
     
                        //调用回调函数
                        if (callbackMethod != null)
                        {
                            callbackMethod(_ex);
                        }
                    });
     
                    //异步开始
                    IAsyncResult iar = acd.BeginInvoke(acb, acd);
                }
                catch (Exception ex)
                {
                    //调用回调函数
                    if (callbackMethod != null)
                    {
                        callbackMethod(ex);
                    }
                }
            }
     
            /// <summary>
            /// 执行异步方法调用
            /// </summary>
            /// <param name="asyncMethod">异步执行的方法</param>
            public static void Process(AsyncEventHandler asyncMethod)
            {
                Process(asyncMethod, null);
            }
        }
  • 相关阅读:
    三种负载均衡 Nginx、Dubbo、Ribbon 区别
    Docker基础学习
    主从复制报错2061:Authentication plugin 'caching_sha2_password' reported error:Authentication require secure connection
    LRU、LFU算法区别
    CAP理论原理
    Mysql安装服务到Window服务列表
    从零开始掌握 HAProxy 负载均衡器,详细!!
    一举拿下Nginx
    Nginx 负载均衡配置误区
    Linux自动化技巧
  • 原文地址:https://www.cnblogs.com/yinggu/p/5195058.html
Copyright © 2011-2022 走看看