| 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. |
| ·VC入门专区 | ·VC高级技术专区 | ||
| ·VC网络通讯编程 | ·VC图像编程 | ||
| ·轻松玩转MFC文档视图架构编程 | |||
| ·深入浅出Win32多线程程序设计 | |||
| ·深入浅出Visual C++动态链接库编程 | |||