程序代码如下:
using System; using System.Threading; namespace AsyncDelegateDemo { delegate void AsyncFoo(int i); class Program { /// <summary> /// 输出当前线程的信息 /// </summary> /// <param name="name">方法名称</param> static void PrintCurrentThreadInfo(string name) { Console.WriteLine("Thread Id of " + name + " is: " + Thread.CurrentThread.ManagedThreadId + ", current thread is " + (Thread.CurrentThread.IsThreadPoolThread ? "" : "not ") + "thread pool thread."); } /// <summary> /// 测试方法,Sleep一定时间 /// </summary> /// <param name="i">Sleep的时间</param> static void Foo(int i) { PrintCurrentThreadInfo("Foo()"); Thread.Sleep(i); } /// <summary> /// 投递一个异步调用 /// </summary> static void PostAsync() { AsyncFoo caller = new AsyncFoo(Foo); //启动异步调用,第一个参数为AsyncFoo委托的参数 //第二个参数为回调函数 //第三个参数为传送给回调函数的参数 // //注意:如果AsyncFoo委托有多个参数,回调函数之前就会有多个参数,和AsyncFoo委托的参数一一对应 //也就是说BeginInvoke的参数个数=AsyncFoo委托的参数个数+2 //加的两个参数分别是:回调函数和传送给回调函数的参数 caller.BeginInvoke(1000, new AsyncCallback(FooCallBack), caller); } /// <summary> /// 异步调用的回调函数 /// </summary> /// <param name="ar"></param> static void FooCallBack(IAsyncResult ar) { PrintCurrentThreadInfo("FooCallBack()"); AsyncFoo caller = (AsyncFoo)ar.AsyncState; caller.EndInvoke(ar); } static void Main(string[] args) { PrintCurrentThreadInfo("Main()"); for (int i = 0; i < 10; i++) { PostAsync(); } Console.ReadLine(); } } }
程序的运行截图如下:
注:
参考文献地址: