日期:2009-06-01  浏览次数:20419 次

Custom Thread Pooling Template
Now that we have covered the basics of Visual Studio .NET project types and templates, let us look at how we can write our own custom project template that will generate a thread pool that can be used by the developer without any modifications at all. Before we start discussing the custom template, let us focus on writing a thread pool class that will be a part of this template.
A thread pool usually consists of two classes: one class that represents a thread, and another class that represents the object that manages a pool of these thread objects. The thread class is fairly simple: it is simply an encapsulation of the built in System.Threading.Thread class, but the thread pool class is slightly more involved. This thread pool class has to create all the threads in the pool, assign them work, and keep track of idle threads so that further work can be assigned to them. Further, the threads in a thread pool are created once, and if a thread is idle, the thread goes into an efficient wait mode (like a sleep call). When there is work to be processed, the thread pool is responsible for bringing an idle thread back into active mode and assigning it work.
Let us start by discussing the thread class first.
public class ThreadPoolThread
{
   public ThreadPoolThread
    (ThreadPool iThreadPool, ThreadPool.DoWork iWorkerMethod)
   {
      mWorkerMethod += iWorkerMethod;

      mThreadPool = iThreadPool;
      mThread = new Thread (new ThreadStart (ThreadFunc));
      mEvent = new AutoResetEvent (false);
      mThread.Start ();
   }

   public void ProcessRequest ()
   {
      mEvent.Set ();
   }

   public void Stop ()
   {
      if (mThread != null)
         mThread.Abort ();
   }

   private void ThreadFunc ()
   {
      WaitHandle[] lWaitHandle = new WaitHandle[1];
      lWaitHandle[0] = mEvent;

      while (true){
         AutoResetEvent.WaitAll (lWaitHandle);
         mWorkerMethod ();
         mThreadPool.ReturnToPool (this);
      }
   }

   private ThreadPool.DoWork mWorkerMethod;
   private Thread mThread;
   private AutoResetEvent mEvent;
   private ThreadPool mThreadPool;
}
This class has four methods, a constructor that sets up the objects required by the class, a method to wake up the thread, a method to kill the thread, and the worker method where the thread will spend its entire life. The ThreadPoolThread object consists of one Thread object and one AutoResetEvent object, which is used to signal an idle thread. The constructor takes in a reference to the thread pool that this thread belongs to, and it also takes in a delegate which is the user defined method that this thread will invoke as part of its processing. The user of this class will pass this delegate, and it typically will be a method that will accept a request (from a socket or from a web service, etc) and process