• C#线程池ThreadPool


    线程池可以减少频繁的线程创建和销毁对系统性能的影响。

    ThreadPool默认是后台属性,IsBackground是true。

    线程池通过线程命名空间的ThreedPool类来实现,要请求由线程池中的一个线程来处理你的任务,需要调用QueueUserWorkItem方法。

    要注意,当你向线程池提交一个人物请求后,你就无法再取消它了。另外,线程池中每个线程按照默认的优先级进行。

    向线程池提交任务使用WaitCallback委托。线程池会对这个任务自动调用一个线程来处理。

    public delegate void WaitCallback(object state);

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace ThreadPoolTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                int newThreads;
                int nCompletionPortThreads;
    
                ThreadPool.SetMaxThreads(10, 200);  //设置线程池的大小
    
                //获取辅助线程数目和异步IO线程数据
                ThreadPool.GetMaxThreads(out newThreads, out nCompletionPortThreads);
                Console.WriteLine("辅助线程数目{0},异步IO线程数目{1}", newThreads, nCompletionPortThreads);
    
    
                for (int i = 0; i < 5; i++)
                {
                    ThreadPool.QueueUserWorkItem(JobForAThread);
                }
    
                Thread.Sleep(3000);
                Console.ReadKey();
            }
    
            static void JobForAThread(object state)
            {
                for (int i = 0; i < 3; i++)
                {
                    Console.WriteLine("循环第{0}次,当前运行的线程ID是{1}", i, Thread.CurrentThread.ManagedThreadId);
                    Thread.Sleep(50);
                }
            }
        }
    }
  • 相关阅读:
    failed to push some refs to 'git@github.com:cq1415583094/MyBatis.git'解决办法
    MyBatis 安装和配置
    MyBatis入门
    LinkedList 源码分析
    ArrayList 源码分析
    什么是注解?
    什么是泛型?
    什么是反射?
    php针对各数据库系统对应的扩展
    DedeCMS文章标题长度最全修改方法
  • 原文地址:https://www.cnblogs.com/Mysterious/p/3429552.html
Copyright © 2020-2023  润新知