普通线程和线程池运行时间对比

  const int intNumber = 500;
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            UseThreads(intNumber);
            sw.Stop();
            Console.WriteLine("用线程执行时间:{0}", sw.ElapsedMilliseconds);
            sw.Reset();
            sw.Start();
            UseThreadPool(intNumber);
            sw.Stop();
            Console.WriteLine("用线程执行时间:{0}", sw.ElapsedMilliseconds);

        }


        private static void UseThreadPool(int numberOfOperation)
        {
            using (var countdown = new CountdownEvent(numberOfOperation))
            {
                Console.WriteLine("开始创建线程:线程池");
                for (int i = 0; i < numberOfOperation; i++)
                { 
                    ThreadPool.QueueUserWorkItem(p=>{
                        Console.WriteLine("{0}", Thread.CurrentThread.ManagedThreadId);
                        Thread.Sleep(TimeSpan.FromSeconds(0.1));
                        countdown.Signal();
                    });
                }
                countdown.Wait();
                Console.WriteLine();
            }
        }

        private static void UseThreads(int numberOfOperation)
        { 
            using(var countdown = new CountdownEvent(numberOfOperation))
            {
                Console.WriteLine("开始创建线程:线程");
                for (int i = 0; i < numberOfOperation; i++)
                {
                    Thread thread = new Thread(() =>
                    {
                        Console.WriteLine("{0}", Thread.CurrentThread.ManagedThreadId);
                        Thread.Sleep(TimeSpan.FromSeconds(0.1));
                        countdown.Signal();

                    });
                    thread.Start();
                }
                countdown.Wait();
                Console.WriteLine();
                
            }
        }
原文地址:https://www.cnblogs.com/sportdog/p/9528231.html