1、定义一个委托
delegate long MyDel(int first, int second);
2、 需异步操作的函数
static int sum(int x,int y) {Console.WriteLine("InSide Sum1");Thread.Sleep(1000);Console.WriteLine("InSide Sum2");return x + y;}
3、回调方法,在异步方法执行完后才执行 ,接收返回结果
static void callback_(IAsyncResult iar)
{Console.WriteLine("Inside CallWhenDone");AsyncResult ar = (AsyncResult)iar; //里氏转换,如果父类中装的是子类的对象,那么可以将这个父类转换为子类对象 Mydel del = (Mydel)ar.AsyncDelegate; //通过AsyncResult类对象的AsyncDelegate属性转化为合适的Mydel委托类型long result = del.EndInvoke(iar);Console.WriteLine("The result is: {0}",result);
}
4、异步调用:
static void Main(string[] args){Mydel Del = new Mydel(sum);Console.WriteLine("Before BeginInvoke");IAsyncResult iar = Del.BeginInvoke(5,6,new AsyncCallback(callback_),Del); //Del焕成null结果也一样Console.WriteLine("Doing more work in main");Thread.Sleep(500);Console.WriteLine("Done with Main.Exiting");Console.ReadKey();}