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);
            }
        }
  • 相关阅读:
    C#8.0——异步流(AsyncStream)
    递归,循环,尾递归
    C#7.2——编写安全高效的C#代码
    Ocelot中文文档-Route
    Ocelot中文文档-Configuration
    Ocelot中文文档-Not Supported
    Ocelot中文文档-Getting Started
    .NET 单元测试的利剑——模拟框架Moq(简述篇)
    输入五个数字,按从大到小的顺序输出
    函数和方法的区别
  • 原文地址:https://www.cnblogs.com/yinggu/p/5195058.html
Copyright © 2011-2022 走看看