并发:线程池异步执行与创建单独的线程执行
线程池与并行度
了解线程池如何工作于大量的异步操作,以及它与创建大量单独的线程的方式的不同之处。
实例代码验证
static void Main(string[] args) { const int numberOfOperations = 500; var sw = new Stopwatch(); sw.Start(); UseThreads(numberOfOperations); sw.Stop(); Console.WriteLine("Thread Execution time using threads: {0}", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); UseThreadPool(numberOfOperations); sw.Stop(); Console.WriteLine("ThreadPool Execution time using threads: {0}", sw.ElapsedMilliseconds); Console.ReadKey(); } static void UseThreads(int numberOfOperations) { using (var countdown = new CountdownEvent(numberOfOperations))//并发执行个数 { Console.WriteLine("Scheduling work by creating threads"); for (int i = 0; i < numberOfOperations; i++) { var thread = new Thread(() => { Console.Write("{0},", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(TimeSpan.FromSeconds(0.1)); countdown.Signal();//注册当前线程 }); //thread.IsBackground = true; thread.Start(); } countdown.Wait(); Console.WriteLine(); } } static void UseThreadPool(int numberOfOperations) { using (var countdown = new CountdownEvent(numberOfOperations))//并发执行个数 { Console.WriteLine("Starting work on a threadpool"); for (int i = 0; i < numberOfOperations; i++) { ThreadPool.QueueUserWorkItem( _ => { Console.Write("{0},", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(TimeSpan.FromSeconds(0.1)); countdown.Signal();//注册当前线程 }); } countdown.Wait(); Console.WriteLine(); } }
Thread Execution time using threads: 5211
ThreadPool Execution time using threads: 5948
结论
线程池为操作系统节省了内存和线程数,但是也为此付出了更长的执行时间。