(一)在线程池中调用委托
代码class Program { private delegate string RunOnThreadPool(out int threadId); static void Main(string[] args) { int threadId = 0; RunOnThreadPool poolDelegate = Test; var t = new Thread(() => Test(out threadId)); t.Start(); t.Join(); Console.WriteLine("Main: Thread id: {0}", threadId); IAsyncResult r = poolDelegate.BeginInvoke(out threadId, Callback, "a delegate asynchronous call"); r.AsyncWaitHandle.WaitOne(); string result = poolDelegate.EndInvoke(out threadId, r); Console.WriteLine("Main: Thread pool worker thread id: {0}", threadId); Console.WriteLine(result); Thread.Sleep(TimeSpan.FromSeconds(2)); Console.WriteLine("Main: End......."); Console.ReadKey(); } private static void Callback(IAsyncResult ar) { Console.WriteLine("Callback: Starting a callback..."); Console.WriteLine("Callback: State passed to a callbak: {0}", ar.AsyncState); Console.WriteLine("Callback: Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread); Console.WriteLine("Callback: Thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId); } private static string Test(out int threadId) { Console.WriteLine("Test: Starting..."); Console.WriteLine("Test: Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep(TimeSpan.FromSeconds(2)); threadId = Thread.CurrentThread.ManagedThreadId; return string.Format("Test: Thread pool worker thread id was: {0}", threadId); } }
代码分析(见下图)