• C#实现简单的委托异步调用


     delegate void textAsy();
            static void Main(string[] args)
            {
    
                textAsy t = texts;
                AsyncCallback callBack = new AsyncCallback(sendCallBack);
                t.BeginInvoke(callBack, new { timeNow= DateTime.Now.Ticks,timeStr=DateTime.Now.ToString() });
                Console.WriteLine(DateTime.Now);
                Console.Read();
            }
            public static void texts()
            {
                Thread.Sleep(1100);
                Console.WriteLine(DateTime.Now);
            }
    
            //3)在回调函数中使用StateObject
            private static void sendCallBack(IAsyncResult ar)
            {
    
                Console.WriteLine("异步状态" + ((dynamic)ar.AsyncState).timeNow + ((dynamic)ar.AsyncState).timeStr);
            }
    

      


    由于操作是异步的 我们不知道他什么时候完成 所以一般采用回调函数处理  
     delegate void textAsy();
            static void Main(string[] args)
            {
    
                textAsy t = texts;
                AsyncCallback callBack = new AsyncCallback(sendCallBack);
                t.BeginInvoke(callBack,DateTime.Now.Ticks);
                Console.WriteLine(DateTime.Now);
                Console.Read();
            }
            public static void texts()
            {
                Thread.Sleep(1100);
                Console.WriteLine(DateTime.Now);
            }
    
            //3)在回调函数中使用StateObject
            private static void sendCallBack(IAsyncResult ar)
            {
    
                Console.WriteLine("异步状态"+(long)ar.AsyncState);
            }
    

      

      

    ar.AsyncState 就是 t.BeginInvoke(callBack,DateTime.Now.Ticks);中的参数
     delegate void textAsy();
            static void Main(string[] args)
            {
    
                textAsy t = texts;
                AsyncCallback callBack = new AsyncCallback(sendCallBack);
                t.BeginInvoke(callBack, new { timeNow= DateTime.Now.Ticks,timeStr=DateTime.Now.ToString() });
                Console.WriteLine(DateTime.Now);
                Console.Read();
            }
            public static void texts()
            {
                Thread.Sleep(1100);
                Console.WriteLine(DateTime.Now);
            }
    
            //3)在回调函数中使用StateObject
            private static void sendCallBack(IAsyncResult ar)
            {
    
                Console.WriteLine("异步状态" + ((dynamic)ar.AsyncState).timeNow + ((dynamic)ar.AsyncState).timeStr);
            }
    

      

  • 相关阅读:
    【二分图匹配入门专题1】L
    【二分图匹配入门专题1】K
    【km算法模板+总结】
    【二分匹配入门专题1】J
    【自定义博客园~~~】
    【二分图匹配入门专题1】I
    【二分图匹配入门专题1】H
    【二分图匹配入门专题1】G
    【二分图匹配入门专题1】E
    【二分图匹配入门专题1】F
  • 原文地址:https://www.cnblogs.com/ProDoctor/p/6136254.html
Copyright © 2020-2023  润新知