zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Bundle 机制
    三次握手和四次挥手
    SparseArray
    ThreadLocal ——android消息机制handler在非主线程创建not called Looper.prepare() 错误的原因
    怎么去除重复代码
    ClassLoader
    android的四种线程池
    LeetCode#50 Pow(x, n)
    LeetCode#49 Anagrams
    LeetCode#48 Rotate Image
  • 原文地址:https://www.cnblogs.com/qixiaolan/p/13434460.html
Copyright © 2011-2022 走看看