惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Help Net Security
Help Net Security
G
Google Developers Blog
雷峰网
雷峰网
WordPress大学
WordPress大学
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Engineering at Meta
Engineering at Meta
Security Latest
Security Latest
T
Threat Research - Cisco Blogs
AWS News Blog
AWS News Blog
F
Full Disclosure
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Exploit Database - CXSecurity.com
J
Java Code Geeks
U
Unit 42
C
Cyber Attacks, Cyber Crime and Cyber Security
V
V2EX
C
Cisco Blogs
博客园 - 司徒正美
Project Zero
Project Zero
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
Blog — PlanetScale
Blog — PlanetScale
Scott Helme
Scott Helme
A
About on SuperTechFans
Hugging Face - Blog
Hugging Face - Blog
S
Securelist
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
G
GRAHAM CLULEY
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyberwarzone
Cyberwarzone
MongoDB | Blog
MongoDB | Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
T
Threatpost
Recorded Future
Recorded Future
C
CXSECURITY Database RSS Feed - CXSecurity.com
宝玉的分享
宝玉的分享
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
The Register - Security
The Register - Security
S
Security Archives - TechRepublic
博客园 - Franky
N
News | PayPal Newsroom
Simon Willison's Weblog
Simon Willison's Weblog
S
SegmentFault 最新的问题
W
WeLiveSecurity
A
Arctic Wolf
B
Blog

博客园 - ph580

国外大牛开发者创造出Siri第三方服务器 HTML5 开发者需要了解的技巧你要知道的知识 VS2008几大新功能描述如下 VS2008和.NET Framework 3.5功能与区别特性 竞争情报的战略与战术运用会让公司得利 为何中国企业在同一个问题上跌倒 开发嵌入式WEB的网络视频监控系统,设计思路 LightSwitch数据源开发小例 Amoeba新版本如何与MYSQL读写分离配置 SQL server 2005 master数据库进行轻型的恢复备份操作 C#多线程窗体控件安全访问实现方法 安全、简单的Windows Forms多线程编程实现 C#编程开发 Berkeley DB SQL使用方法 装箱和拆箱(什么是装箱和拆箱) C#基础 WCF中使用SoapHeader进行验证实现方法总结 JavaScript 正则表达式解析常用方法 C#正则表达式无法识别双引号解决 ASP.NET服务器控件开发之实现事件分析 Asp.net控件开发学习之数据回传小节
如何下手进行高效的c#线程池设计
ph580 · 2011-07-16 · via 博客园 - ph580

在实际使用中,容易造成CPU占用偏高,笔者分析认为是由于信号量本身的缺点造成的,因此笔者重新设计了一款更高效的c#线程池,完全不使用waithandle之类的阻塞线程,而是使用更为简单的最大线程数值(一个long整数)来控制线程的运行。如果超过指定的线程数,那么保存在hash表中的线程进入等待队列,当有空闲位置时,才会释放出一个等待队列中的线程启动并运行。

笔者粗略地计算了下,此种方法比基于信号量的效率要高30左右,性能提高是显著的^_^pdf,下面为大家展示代码。

    public class MyThreadManager : MyThreadPool, iThreadManager
    { //线程池的启动、停止控制大同小异,不再赘述pdf
        private bool bStart;
        private bool bPause;
        private bool bStoped;

        public bool Running
        {
            get { return bStart && !bPause && !bStoped; }
        }
        public MyThreadManager(int num):base(num)
        {
            ControlCallback = new ThreadControl(Run);
            bStart = false;
            bPause = false;
            bStoped = false;
        }

        public virtual void Start()
        {
            bStart = true;
            bPause = false;pdf
            bStoped = false;
        }

        public void Stop()
        {
            bPause = true;
            bStart = false;
            bStoped = false;
        }

        public void Pause()
        {
            bStoped = true;
            bStoped = false;
            bPause = false;
        }

        public void Resume()
        {
            bPause = false;
            bStoped = false;
            bStart = true;
        }

        public void Run()
        {
            while(!bStart || bPause || bStoped){
                if (bStoped)
                {
                    Thread.CurrentThread.Abort();
                }
                Thread.Sleep(20);
            }
            while (Interlocked.Read(ref iRunningThreadNum) > Interlocked.Read(ref iMaxThreadNum))
            {
                Thread.Sleep(20);
            }
            Interlocked.Increment(ref iRunningThreadNum); //增加线程池中运行的线程数量
        }
    }

    public class MyThreadPool
    {
        protected Hashtable  m_Pool;
        protected Queue<string> m_Queue;

        protected ThreadControl m_control;

        public ThreadControl ControlCallback
        {
            set
            {
                m_control = value;
            }
            get
            {
                return m_control;
            }
        }

        protected long iMaxThreadNum;
        public  long MaxThreadNum
        {
            get
            {
                return Interlocked.Read(ref iMaxThreadNum);
            }
        }

        private long iQueueSize;

        protected long iRunningThreadNum;

        public long RunningThreadNum
        {
            get { return Interlocked.Read(ref iRunningThreadNum); }
        }

        public MyThreadPool(int num)
        {
            iMaxThreadNum = num;
            iRunningThreadNum = 0;
            iQueueSize = 0;
            m_Pool = new Hashtable(num);
            m_Queue = new Queue<string>();
        }

        public void QueueWorkItem(ThreadCallback callback, object obj)
        {

            Thread thread = new Thread(delegate()
            {
                if (m_control != null)
                    m_control();
                callback(obj); //这里是实际执行的函数
                m_Pool.Remove(Thread.CurrentThread.Name); //将当前线程移出线程池
                Interlocked.Decrement(ref iRunningThreadNum); //运行线程数递减
                ReleaseQueue(); //释放等待队列中的线程
            });
            string threadGuid = Guid.NewGuid().ToString();
            thread.Name = threadGuid; //保证线程命名唯一
            m_Pool.Add(threadGuid,thread);
            if (Interlocked.Read(ref iRunningThreadNum) < Interlocked.Read(ref iMaxThreadNum))
            {
                thread.Start();
            }
            else
            {
                m_Queue.Enqueue(thread.Name);
                Interlocked.Increment(ref iQueueSize);
            }
        }

        private void ReleaseQueue() //如果等待队列中有线程存在则释放一个,并做减计数
        {
            if (Interlocked.Read(ref iQueueSize) > 0)
            {
                string threadname = "";
                lock (m_Queue)
                {
                   threadname = m_Queue.Dequeue();
                   Interlocked.Decrement(ref iQueueSize);
                }
                Thread t = m_Pool[threadname] as Thread;
                t.Start();
            }
        }
    }

    public interface iThreadManager
    {

        void Start();
        void Stop();
        void Pause();
        void Resume();

        void Run();
    }
}