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

来源:互联网 发布:python turtle 国旗 编辑:程序博客网 时间:2024/04/26 13:51

 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