一个C#实现异步调用的简单范例代码
代码转自:http://blog.csdn.net/mypc2010/
/* * User: MXi4oyu * Email:798033502@qq.com * Date: 2013-7-18 * Time: 19:50 * */ using System; using System.Threading; using System.Runtime.Remoting.Messaging; namespace Test { class Program { //定义一个委托 public delegate int BinaryOp(int x,int y); public static void Main(string[] args) { //输出执行Main方法的线程ID Console.WriteLine("Main() invoked on thread{0}",Thread.CurrentThread.ManagedThreadId); //BinaryOp 委托指向Add方法 BinaryOp b = new Program.BinaryOp(Add); IAsyncResult iftAR = b.BeginInvoke(10,10,new AsyncCallback(AddComplete),null); Console.WriteLine("不等它,咱继续!"); Console.ReadKey(); } static void AddComplete(IAsyncResult itfAR) { Console.WriteLine("Addcomplete invoked on thread{0}",Thread.CurrentThread.ManagedThreadId); Console.WriteLine("your addtion is complete"); //得到结果 AsyncResult ar = (AsyncResult)itfAR; BinaryOp b = (BinaryOp)ar.AsyncDelegate; Console.WriteLine("10+10={0}",b.EndInvoke(itfAR)); } static int Add(int x,int y) { Console.WriteLine("Add () invoked on thread{0}",Thread.CurrentThread.ManagedThreadId); Thread.Sleep(5000); return x+y; } } }