委托的异步执行

    public delegate int mydelegate(int x, int y);
    class Program
    {
      
        static void Main(string[] args)
        {
            Console.WriteLine("Main中正在执行的线程ID:{0}",Thread.CurrentThread.ManagedThreadId);
            ///实例化一个委托
            mydelegate d = new mydelegate(Add);
            //委托的同步调用
            //int resuit = d.Invoke(2, 4);
            //Console.WriteLine("2+4 is={0}",resuit);

            ///委托的异步调用
            ///生成BeginInvoke的方法是 public IAsyncResult BeginInvoke(int x,int y,AsyncCallBack cb,Object state)
            ///生成EndInvoke的方法是 public int EndInvoke(IAsyncResult result)
            ///BeginInvoke和EndInvoke是一种耦合机制,EndInvoke需要一个IAsyncResult类型参数,BeginInvoke返回的是IAsyncResult
            //IAsyncResult IResuit = d.BeginInvoke(2, 3, null, null);
            //int AsyncResuit = d.EndInvoke(IResuit);
            //Console.WriteLine("2+4 is={0}",AsyncResuit);

            ///同步调用线程
            ///
            //IAsyncResult IResuit = d.BeginInvoke(2, 4, null, null);
            //while (!IResuit.IsCompleted)
            //{
            //    Console.WriteLine("Doing more work in Main()");
            //    Thread.Sleep(1000);
            //}
            //int AsyncResuit = d.EndInvoke(IResuit);
            //Console.WriteLine("2+4 is={0}", AsyncResuit);


            //IAsyncResult IResuit = d.BeginInvoke(2, 4, null, null);
            //while (IResuit.AsyncWaitHandle.WaitOne(1000, true))
            //{
            //    Console.WriteLine("Doing more work is Main");
            //}

            ///当BeginInvoke处理完数据后调用AsyncCallback
            ///通过次线程通知主线程,这样子比主线程频繁询问次线程要好些。
            IAsyncResult IResuit = d.BeginInvoke(2, 3, new AsyncCallback(AddComplete), null);


            //int AsyncResuit = d.EndInvoke(IResuit);
            //Console.WriteLine("2+4 is={0}", AsyncResuit);

            Console.ReadKey();
        }
      
        static void AddComplete(IAsyncResult resut)
        {
            Console.WriteLine("addComplete线程ID:{0}",Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("you addition is complete");
            /// AsyncResult定义在了System.Runtime.Remoting.Messaging;
            /// 该类的mydelegate返回了原始异步委托的应用,这个地方就是
            /// public delegate int mydelegate(int x, int y);
            /// 这样子写的原因是BeginInvoke处理完了后,会调用AsyncCallback,但是他访问不到定义在Main中的EndInvoke
            AsyncResult r = (AsyncResult)resut;
            mydelegate b = (mydelegate)r.AsyncDelegate;
            Console.WriteLine(b.EndInvoke(resut));
        
        }

        static int Add(int x, int y)
        {
            Console.WriteLine("Add方法中正在执行的线程ID:{0}",Thread.CurrentThread.ManagedThreadId);

            //暂停一下,模拟一个耗时的操作
            Thread.Sleep(5000);
            return x + y;
        }
       
    }

 

posted @ 2013-06-05 15:01  xinyebs  阅读(134)  评论(0编辑  收藏  举报