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对委托进行适当清理
//