using System;using System.Threading;namespace AsyncDelegateDemo{ delegate void AsyncFoo(int i); class Program { /// <summary> /// 输出当前线程的信息 /// </summary> /// <param name="name">方法名称</param> static void PrintCurrThreadInfo(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) { PrintCurrThreadInfo("Foo()"); Thread.Sleep(i); } /// <summary> /// 投递一个异步调用 /// </summary> static void PostAsync() { AsyncFoo caller = new AsyncFoo(Foo); caller.BeginInvoke(1000, new AsyncCallback(FooCallBack), caller); } static void Main(string[] args) { PrintCurrThreadInfo("Main()"); for(int i = 0; i < 10 ; i++) { PostAsync(); } Console.ReadLine(); } static void FooCallBack(IAsyncResult ar) { PrintCurrThreadInfo("FooCallBack()"); AsyncFoo caller = (AsyncFoo) ar.AsyncState; caller.EndInvoke(ar); } }}
这段代码代码的输出如下:Thread Id of Main() is: 1, current thread is not thread pool thread.Thread Id of Foo() is: 3, current thread is thread pool thread.Thread Id of FooCallBack() is: 3, current thread is thread pool thread.Thread Id of Foo() is: 3, current thread is thread pool thread.Thread Id of Foo() is: 4, current thread is thread pool thread.Thread Id of Foo() is: 5, current thread is thread pool thread.Thread Id of FooCallBack() is: 3, current thread is thread pool thread.Thread Id of Foo() is: 3, current thread is thread pool thread.Thread Id of FooCallBack() is: 4, current thread is thread pool thread.Thread Id of Foo() is: 4, current thread is thread pool thread.Thread Id of Foo() is: 6, current thread is thread pool thread.Thread Id of FooCallBack() is: 5, current thread is thread pool thread.Thread Id of Foo() is: 5, current thread is thread pool thread.Thread Id of Foo() is: 7, current thread is thread pool thread.Thread Id of FooCallBack() is: 3, current thread is thread pool thread.Thread Id of Foo() is: 3, current thread is thread pool thread.Thread Id of FooCallBack() is: 4, current thread is thread pool thread.Thread Id of FooCallBack() is: 6, current thread is thread pool thread.Thread Id of FooCallBack() is: 5, current thread is thread pool thread.Thread Id of FooCallBack() is: 7, current thread is thread pool thread.Thread Id of FooCallBack() is: 3, current thread is thread pool thread.
从输出可以看出,.net使用delegate来“自动”生成的异步调用是使用了另外的线程( 而且是线程池线程)。转载于:https://www.cnblogs.com/GeneralXU/archive/2009/05/27/1490522.html
相关资源:C#多线程与异步的区别详解