把做工程过程常用的代码段备份一下,下边代码是关于一个C#实现异步调用的简单范例的代码。
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) { Console.WriteLine(“Main() invoked on thread{0}”,Thread.CurrentThread.ManagedThreadId); 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;
}
}
}
|