委托的异步调用(2)

2008-06-29 20:49

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

namespace 委托的异步调用
{
    public delegate int DelegateClass(out DateTime start,out DateTime stop);//定义委托分类DelegateClass
    class Starter
    {
        static void Main(string[] args)
        {
            DelegateClass del = MethodA;//定义委托对象del
            DateTime start;
            DateTime stop;
            IAsyncResult ar = del.BeginInvoke(out start, out stop, null, null); ;// 开始委托的异步调用
         
            ar.AsyncWaitHandle.WaitOne();

            int elapse = del.EndInvoke(out start, out stop, ar);
            Console.WriteLine("starttime:{0}", start.ToString());
          Console.WriteLine("stoptime{0}",stop.ToString());
          Console.WriteLine("elapsetime:{0}", elapse.ToString());
        }
      
        public static int MethodA(out DateTime start,out DateTime stop)
        {
            start = DateTime.Now;
            Thread.Sleep(5000);
            stop = DateTime.Now;
            return (stop - start).Seconds;
        }
     }
   
}
//注:在异步操作函数完成之前调用EndInvoke方法,会阻塞对方,直到该操作完成为止,对于每个
//BeginInvoke都应该有一个EndInvoke与之对应,确认操作结果,检测异常,允许CLR对委托进行适当清理
//

posted @ 2010-02-03 09:37  玄魂  阅读(224)  评论(0编辑  收藏  举报