c#線程池ThreadPool實例詳解

1. 如何查看線程池的最大線程數和最小線程數spa

        static void Main(string[] args)
        {
            Console.WriteLine("----------線程池開始,線程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

            int workthread;
            int iothread;

            ThreadPool.GetMaxThreads(out workthread, out iothread);
            Console.WriteLine("Max Work Thread:{0} Max I/O Thread:{1}",workthread,iothread);

            ThreadPool.GetMinThreads(out workthread, out iothread);
            Console.WriteLine("Mix Work Thread:{0} Mix I/O Thread:{1}", workthread, iothread);

            Console.WriteLine("----------線程池結束,線程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

            Console.Read();
        }


image

2. 如何設置線程池的最大線程數和最小線程數線程

        static void Main(string[] args)
        {
            Console.WriteLine("----------線程池開始,線程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

            int workthread = 8;
            int iothread = 8;

            ThreadPool.SetMaxThreads(workthread, iothread);
            Console.WriteLine("Max Work Thread:{0} Max I/O Thread:{1}",workthread,iothread);

            ThreadPool.SetMinThreads(workthread, iothread);
            Console.WriteLine("Mix Work Thread:{0} Mix I/O Thread:{1}", workthread, iothread);

            Console.WriteLine("----------線程池結束,線程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

            Console.Read();
        }


image


3. ThreadPool線程啓動code

        static void Main(string[] args)
        {
            Console.WriteLine("----------線程池開始,線程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

            for (int i = 0; i < 5; i++)
            {
                string name = string.Format("ThreadPool_{0}", i);
                WaitCallback method = (t) => Program.TestThread(t.ToString());
                ThreadPool.QueueUserWorkItem(method,name);
            }

            Console.WriteLine("----------線程池結束,線程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId);

            Console.Read();
        }

        static void TestThread(string name)
        {
            Console.WriteLine("TestThread Start name:{0} 當前線程id:{1} 當前時間:{2}", name, Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yy-MM-dd hh:mm:ss.fff"));

            long sum = 0;

            for (int i = 0; i < 10000000; i++)
            {
                sum += i;
            }

            Console.WriteLine("TestThread End name:{0} 當前線程id:{1} 當前時間:{2}", name, Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yy-MM-dd hh:mm:ss.fff"));
        }


image


4. ThreadPool線程回收orm

ThreadPool線程池會自動回收。blog


5. ThreadPool線程池等待get

能夠經過ManualResetEvent信號量來實現,代碼以下:string


6. ThreadPool返回值it

沒有提供方法,能夠本身定義,代碼以下:io


7. ThreadPool回調方法class

沒有提供方法,能夠本身定義,代碼以下:

相關文章
相關標籤/搜索