异步委托调用和回调函数的结合使用

 using System;
using System.Runtime.Remoting.Messaging;

namespace ConsoleApplication17
{
    public delegate string MyDelegate();
    /// <summary>
    /// Class1 的摘要说明。
    /// </summary>
    class Class1
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO: 在此处添加代码以启动应用程序
            //
            Class1 c1=new Class1();
            MyDelegate d=new MyDelegate(c1.M);
            Console.WriteLine("Start...");
            //异步委托调用
            d.BeginInvoke(new System.AsyncCallback(c1.CallBackFun),"heihei");

            //程序会继续执行
            Console.WriteLine("going next...");
            Console.ReadLine();
        }

        public void CallBackFun(IAsyncResult res)
        {

            //获取所调用异步委托的最后一个参数,这个参数可以是一个
            //自定义的参数类型
            string arg=(string)res.AsyncState;

            //将res强制转换从BeginInvoke获取的IAsyncResult
            AsyncResult a=(AsyncResult)res;
            //获取在其上调用异步调用的委托对象
            MyDelegate temp=(MyDelegate)a.AsyncDelegate;
            //获取异步委托调用的返回值
            string s=(string)temp.EndInvoke(res);

            //打印
            Console.WriteLine("the last arg from the delegate is {0}",arg);
            Console.WriteLine("the string return from the M method is {0}",s);
            
        }
        public string M()
        {
            Console.WriteLine("do something slow...");
            //返回值
            return "good";
        }
    }
}

结果:

Start...
going next...
do something slow...
the last arg from the delegate is heihei
the string return from the M method is good

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值