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;
            });
        }

    }

}

  

转载于:https://www.cnblogs.com/zxiong/p/10594108.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值