线程池

https://msdn.microsoft.com/zh-cn/library/system.threading.threadpool(v=vs.110).aspx

最基础的

 class Program
    {
        static void Main(string[] args)
        {
            int oldMaxWorkingThreads, oldMaxCompletionPortThreads;

            ThreadPool.GetMaxThreads(out oldMaxWorkingThreads, out oldMaxCompletionPortThreads);

            int oldMinWorkingThreads, oldMinCompletionPortThreads;

            ThreadPool.GetMinThreads(out oldMinWorkingThreads, out oldMinCompletionPortThreads);

            Console.WriteLine(string.Format("oldMaxWorkingThreads={0},oldMaxCompletionPortThreads={1}", oldMaxWorkingThreads, oldMaxCompletionPortThreads));
            Console.WriteLine(string.Format("oldMinWorkingThreads={0},oldMinCompletionPortThreads={1}", oldMinWorkingThreads, oldMinCompletionPortThreads));

            Console.WriteLine(Environment.ProcessorCount);//cpu的核数

            Console.ReadKey();
        }
    }

 

线程池QueueUserWorkItem中方法没有执行

 [Test]
        public void Test()
        {
            try
            {
                int count = 20;
                List<byte[]> list = new List<byte[]>();
                Random random = new Random();
                for (int i = 0; i < count; i++)
                {
                    byte[] buffer = new byte[i + 1];
                    for (int j = 0; j < buffer.Length; j++)
                    {
                        //buffer[j] = (byte)random.Next(0, 7);
                        buffer[j] = (byte) (i + 1);
                    }

                    list.Add(buffer);
                }

              
                for (int i = 0; i < count; i++)
                {
                    Console.WriteLine($@"i = {i}, length={list[i].Length}");
                    ThreadPool.QueueUserWorkItem(Test, list[i]);
                }
  Thread.Sleep(5000);
} catch (Exception ex) { LogUtil.CreateLog(LogLevel.Error, ex); } }

https://stackoverflow.com/questions/9196987/using-c-sharp-queueuserworkitem-doesnt-seem-to-execute-all-the-methods

ThreadPool threads are background threads, meaning they are aborted once your main thread ends.

Since no one guarantees that your async methods will have a chance to execute before the last statement, you will get different results each time.

需要在上面的Test方法中添加  Thread.Sleep(5000);确保子线程工作结束之前,主线程没有退出

 

ThreadPool执行QueueUserWorkItem的时候,后台有Thread Aborted的错误日志

同样是因为主线程退出导致的问题

 

 

 

 

 

 

http://blog.zhaojie.me/2009/07/thread-pool-1-the-goal-and-the-clr-thread-pool.html

浅谈线程池(上):线程池的作用及CLR线程池

http://www.cnblogs.com/JeffreyZhao/archive/2009/07/24/thread-pool-2-dedicate-pool-and-io-pool.html  

浅谈线程池(中):独立线程池的作用及IO线程池

http://blog.zhaojie.me/2009/10/thread-pool-3-lab.html

浅谈线程池(下):相关试验及注意事项

 

posted @ 2015-05-15 10:12  ChuckLu  阅读(204)  评论(0编辑  收藏  举报