welcome to Qijie's Blog 薛其杰


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;           //AsyncResult需要此命名空间
using System.Threading;                        //Thread.Sleep(5000)需要此命名空间

namespace DelegateAsyncCall
{  
    public delegate int BinaryOp(int larg, int rarg);
    class Program
    {
        static void Main(string[] args)
        {
            BinaryOp b = new BinaryOp(Add);
            IAsyncResult ifR = b.BeginInvoke(10, 10, new AsyncCallback(AddComplete), null);
            //Main Thread.. 模拟主线程所操作
            for (int i = 0; i < 50; i++)
            {
                Console.WriteLine("Main thread...");
            }
            Console.Read();
        }

        static int Add(int larg, int rarg)
        {
            try
            {
                int.Parse(larg.ToString());
                int.Parse(rarg.ToString());
            }
            catch
            {
                throw new ArgumentException("Integer arguments needed");
                return 0;
            }
            Thread.Sleep(5000);       //增加延时, shide
            return larg + rarg;
        }

        static void AddComplete(IAsyncResult iaR)
        {
            AsyncResult aR= (AsyncResult)iaR;
            BinaryOp b = (BinaryOp)aR.AsyncDelegate;
            Console.WriteLine("Adding results is {0}",b.EndInvoke (iaR));
            Console.Read();
        }
    }
}

posted on 2009-10-16 09:06  零点零一  阅读(311)  评论(0编辑  收藏  举报