zoukankan      html  css  js  c++  java
  • delegate异步

    using System;
    using System.Runtime.Remoting.Messaging;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace LCS.WeiXin.Transfer
    {
        class Program
        {
            public delegate int AddHandler(int a, int b, int c);
    
            static void Main()
            {
                Func<int, int, int, int> fun = AddClass.Add;
                //  fun.BeginInvoke(1, 2, 3, CallbackFunc, null);
                Console.WriteLine("===== 异步回调 AsyncInvokeTest =====");
                AddHandler handler = new AddHandler(AddClass.Add);
                //异步操作接口(注意BeginInvoke方法的不同!)
                IAsyncResult result = handler.BeginInvoke(1, 2, 3, new AsyncCallback(CallbackFunc), "AsycState:OK");
                Console.WriteLine("------继续做别的事情。。。--------");
                Console.ReadKey();
    
            }
    
            public static void CallbackFunc(IAsyncResult result)
            {
                //result 是“加法类.Add()方法”的返回值             
                //AsyncResult 是IAsyncResult接口的一个实现类,引用空间:System.Runtime.Remoting.Messaging             
                //AsyncDelegate 属性可以强制转换为用户定义的委托的实际类。
                Func<int, int, int, int> fun = AddClass.Add;
                AddHandler handler = (AddHandler)((AsyncResult)result).AsyncDelegate;
                // fun.EndInvoke(result);
                Console.WriteLine(handler.EndInvoke(result));
                Console.WriteLine(result.AsyncState);
            }
    
            public class AddClass
            {
                public static int Add(int a, int b, int c)
                {
                    Console.WriteLine("
    开始计算:" + a + "+" + b + "+" + c);
                    Thread.Sleep(3000); //模拟该方法运行三秒
                    Console.WriteLine("计算完成!");
                    return a + b + c;
                }
            }
    
            static async void Async2()
            {
                await Task.Run(() => { Thread.Sleep(5000); Console.WriteLine("bbb"); });
                Console.WriteLine("ccc");
            }
    
            public static Task<int> ForTest()
            {
                return Task.Factory.StartNew<int>(() =>
                {
                    Console.WriteLine("ddd");
                    return 1;
                });
            }
    
        }
    
    }
    

      

  • 相关阅读:
    CompareUtil
    linux awk学习笔记
    linux用grep查找包含两个关键字的命令
    mysql 使用set names 解决乱码问题
    对私有静态方法进行单测
    使用JUnit测试预期异常
    Tortoise svn 冲突解决主要办法
    tortoise svn冲突解决
    word-break与word-wrap
    移动端适配
  • 原文地址:https://www.cnblogs.com/zxiong/p/10594108.html
Copyright © 2011-2022 走看看