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("\n开始计算:" + 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;
            });
        }

    }

}

  

上一篇:JiJiDown


下一篇:通知,代理,KVO的区别,以及通知的多线程问题