Brief introduction
Creating threads is an expensive operation, and creating threads for each transient asynchronous operation can incur significant overhead.
Invoking delegates in a thread pool
1 usingSystem;2 usingSystem.Threading;3 4 namespaceChapter3.recipe15 {6 class Program7 {8 Static voidMain (string[] args)9 {Ten intThreadId =0; One ARunonthreadpool pooldelegate =Test; - - vart =NewThread (() = Test ( outthreadId)); the T.start (); - T.join (); - -Console.WriteLine ("Thread ID: {0}", threadId); + - //call BeginInvoke () to run the delegate, and the callback function is called after the asynchronous operation completes + //The BeginInvoke () call returns immediately after the worker thread in the thread pool is allowed to continue other work while the asynchronous operation is performed. AIAsyncResult r = Pooldelegate.begininvoke ( outThreadId, Callback,"a delegate asynchronous call"); atR.asyncwaithandle.waitone ();//wait for the asynchronous operation to complete - //in fact EndInvoke () waits for the completion of the asynchronous operation, so R. Asyncwaithandle.waitone (); not necessary. - stringresult = Pooldelegate.endinvoke ( outThreadId, R); - //when the asynchronous operation is complete, the callback function is placed in the thread pool, which is exactly a worker thread. -Console.WriteLine ("thread pool worker thread ID: {0}", threadId); - Console.WriteLine (result); in -Thread.Sleep (Timespan.fromseconds (2)); to } + - Private Delegate stringRunonthreadpool ( out intthreadId); the * Private Static voidCallback (IAsyncResult ar)//callback function $ {Panax NotoginsengConsole.WriteLine ("starting a callback ..."); -Console.WriteLine ("State passed to a callbak: {0}", AR. asyncstate); theConsole.WriteLine ("is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread); +Console.WriteLine ("thread pool worker thread ID: {0}", Thread.CurrentThread.ManagedThreadId); A } the + - Private Static stringTest ( out intthreadId) $ { $Console.WriteLine ("starting ..."); -Console.WriteLine ("is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread); -Thread.Sleep (Timespan.fromseconds (2)); theThreadId =Thread.CurrentThread.ManagedThreadId; - return string. Format ("thread pool worker thread ID was: {0}", threadId);Wuyi } the } -}
Methods such as using the Beginoperationname/endoperation method and the IAsyncResult object in. NET are called Asynchronous programming models , which are called async methods.
Using the thread pool