using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace CYSThreadPool { public delegate void StartupMethod(); /// <summary> /// thread pool /// </summary> class CYSThreadPool { private ReusableThread[] m_ThreadPool; public CYSThreadPool(int pSize) { m_ThreadPool = new ReusableThread[pSize]; for (int i = 0; i < pSize; i++) { m_ThreadPool[i] = new ReusableThread(); } } /// <summary> /// 取得一个可用线程 /// </summary> /// <returns> /// Thread OR NULL /// </returns> public ReusableThread GetThread() { lock (this) { ReusableThread vThread = GetAvailableThread(); return vThread; } } private ReusableThread GetAvailableThread() { ReusableThread vReturnThread = null; foreach (ReusableThread vThread in m_ThreadPool) { if (vThread.IsAvailable) { vThread.IsAvailable = false; vReturnThread = vThread; break; } } return vReturnThread; } /// <summary> /// 取得可用线程数 /// </summary> /// <returns></returns> public int GetAvailableThreadCount() { lock (m_ThreadPool) { if (m_ThreadPool == null || m_ThreadPool.Length == 0) { return 0; } int count = 0; for (int i = 0; i < m_ThreadPool.Length; i++) { if (m_ThreadPool[i].IsAvailable == true) count++; } return count; } } /// <summary> /// recover the state Available ,for using next time. /// </summary> /// <param name="pThread"></param> public void PutThread(ReusableThread pThread) { lock (this) { pThread.IsAvailable = true; } } } class ReusableThread { private Thread m_Thread; private bool isAvailable = true; public bool IsAvailable { get { return isAvailable; } set { isAvailable = value; } } private StartupMethod m_StartupMethod; public ReusableThread() { m_Thread = new Thread(new ThreadStart(CommonStart)); } /// <summary> /// 阻塞调用线程,直到某个线程终止时为止 /// </summary> public void Join() { if (m_Thread.ThreadState == ThreadState.Running) { m_Thread.Join(); } } /// <summary> /// 调用此方法通常会终止线程 /// </summary> public void Abort() { if (m_Thread.ThreadState != ThreadState.Aborted) { m_Thread.Abort(); } } /// <summary> /// 已过时。挂起线程,或者如果线程已挂起,则不起作用。 /// </summary> public void Suspend() { if (m_Thread.ThreadState != ThreadState.Suspended) { m_Thread.Suspend(); } } public void Run(StartupMethod pStartupMethod) { m_StartupMethod = pStartupMethod; m_Thread.Start(); } public void Run() { m_Thread.Start(); } public void CommonStart() { if (m_StartupMethod != null) { m_StartupMethod(); m_StartupMethod = null; } else { Run(); } } } } public void RunWithThread() { CYSThreadPool vPool = new CYSThreadPool(20); ReusableThread vThread = vPool.GetThread(); if (vThread == null) { return; } else { vThread.Run(new StartupMethod(MyCode)); vThread.Join(); vPool.PutThread(vThread); } } public void MyCode() { Thread.Sleep(2000); }