C#_delegate - 异步调用实例 BeginInvoke EndInvoke event

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace EventClock
{

    public class ClassWithDelegate
    { 
        //封装了一个返回值为int的多重委托方法
        public delegate int DelegateThatReturns();

        public event DelegateThatReturns theDelegate;

        public void Run()
        {
            for (; ; )
            {
                Thread.Sleep(500);

                if (theDelegate != null)
                {
                    //显式调用每个委托方法
                    foreach (DelegateThatReturns del in theDelegate.GetInvocationList())
                    {
                        //异步调用
                        //传入委托作为一个状态对象
                        del.BeginInvoke(new AsyncCallback(ResultReturns), del);
                       
                    }
                    Console.WriteLine();
                }
            }
        }
        //获取结果的回调方法
        public void ResultReturns(IAsyncResult iar)
        {
            //将状态对象转换为委托类型
            DelegateThatReturns del = (DelegateThatReturns)iar.AsyncState;
            //调用委托的EndInvoke方法获取结果
            int result = del.EndInvoke(iar);
            //显示结果
            Console.WriteLine("Delegate returned result: {0}",result);
        }
    }

    public class FirstSubscribe
    {
        private int myCounter = 0;

        public void Subscribe(ClassWithDelegate theClassWithDelegate)
        {
            theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturns(DisplayCounter);
        }

        public int DisplayCounter()
        {
            Console.WriteLine("Busy in displaying............");
            Thread.Sleep(10000);
            Console.WriteLine("Do not with work in display............");
            return ++myCounter;
        }
    }
    public class SecondSubscribe
    {
        private int myCounter = 0;

        public void Subscribe(ClassWithDelegate theClassWithDelegate)
        {
            theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturns(Doubler);
        }

        public int Doubler()
        {
            return myCounter += 2;
        }
    }


    

    class Program
    {
        static void Main(string[] args)
        {
            ClassWithDelegate theClassWithDelegate = new ClassWithDelegate();

            FirstSubscribe fs = new FirstSubscribe();
            fs.Subscribe(theClassWithDelegate);

            SecondSubscribe ss = new SecondSubscribe();
            ss.Subscribe(theClassWithDelegate);

            theClassWithDelegate.Run();
            
            Console.ReadLine();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值