usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespacethread Pool {classProgram {Static voidMain (string[] args) { //WaitCallback//Thread pool threads are background threads//threading Advantage of thread pools: threads can be reused to improve thread utilization//Thread pool Find an idle thread to perform this task for us, and when the task is complete, it is not immediately released//instead, go back to the thread pool and keep doing other tasks.//thread switching consumes resources, and when the CPU switches threads, it is necessary to keep the state of the current thread execution in the register. //thread creation consumes resources very much. Thread creation is very full and consumes a lot of memory space. Minimum 1 m memory cost per thread. //because operating system switching threads consume a significant amount of time and resources, it is not necessarily more efficient for the threads to perform more efficiently//maximum line in thread pool book: 1024 default of 1000//minimum number of threads: 4, default is 4 (varies by CPU)//1 Cores: 255 threads, 4*255=1000ThreadPool.QueueUserWorkItem ((s) = ={Console.WriteLine (s); }, "JJ"); #regionCompare the speed of threads and thread poolsStopwatch SP=NewStopwatch (); Sp. Start (); for(inti =0; I < -; i++ ) { NewThread (() = { intMM = i *2+2-3*3; }); } sp. Stop (); Console.WriteLine ("number of milliseconds spent on 100 threads:"+sp. Elapsed.totalmilliseconds); Sp. Restart (); for(intj =0; J < -; j + +) {ThreadPool.QueueUserWorkItem (s)= { intnn = J *2+2-3*3; }); } sp. Stop (); Console.WriteLine ("the number of milliseconds the thread pool spends:"+sp. Elapsed.totalmilliseconds); #endregionConsole.readkey (); } }}
Thread pool and multithreaded execution time comparison