C# 线程池

为什么要用线程池?

不需要重复新开销毁线程

环境: vs 2015  .net 4.5.2  输出环境:控制台应用程序

贴代码:

    class Program
    {
        static int workerThreads;//线程池中辅助线程的最大数目
        static int completionPortThreads;//线程池中异步 I/O 线程的最大数目

        static AutoResetEvent myEvent = new AutoResetEvent(false);//默认阻塞
        
        static void Main(string[] args)
        {
            Console.WriteLine("Begin in Main");

            ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);

            Console.WriteLine($"workerThreads:{workerThreads} completionPortThreads:{completionPortThreads}");

            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadDo));

            Console.WriteLine("End in Main");

            myEvent.WaitOne();//是否阻塞  阻塞条件 1、信号点 AutoResetEvent 为false  2、myEvent.Set();

            Console.WriteLine("线程池终止!");

            Console.ReadKey();
        }
        static void ThreadDo(Object o)
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(DateTime.Now.ToString() + "[Thread " + (int)i + "] Execute in ThreadDo");
                Thread.Sleep(100);
            }
            myEvent.Set();//给信号灯赋值 让UI线程继续执行  不赋值Ui无限等待
        }
    }
View Code

 

你可能感兴趣的:(C# 线程池)