应一个同事之托,写了段简单的代码来完成排队执行的目的,环境为.net 2.0(vs2005),代码如下:

   1:          /// <summary>
   2:          /// 最大并发任务数
   3:          /// </summary>
   4:          private readonly int maxConcurrentTask = 10;
   5:          /// <summary>
   6:          /// 信号
   7:          /// </summary>
   8:          private readonly object semaphore = new object();
   9:          /// <summary>
  10:          /// 排队中的任务数
  11:          /// </summary>
  12:          private volatile int taskQueuing = 0;
  13:          /// <summary>
  14:          /// 执行中的任务数
  15:          /// </summary>
  16:          private volatile int taskRunning = 0;
  17:   
  18:          /// <summary>
  19:          /// 排任务
  20:          /// </summary>
  21:          /// <param name="task">任务</param>
  22:          public void QueueTask(object task)
  23:          {
  24:              do
  25:              {
  26:                  // 预防线程池过载
  27:                  if (taskQueuing + taskRunning < maxConcurrentTask)
  28:                  {
  29:                      System.Threading.Interlocked.Increment(ref taskQueuing);
  30:                      if (System.Threading.ThreadPool.QueueUserWorkItem(RunTask, task))
  31:                          return;
  32:                      System.Threading.Interlocked.Decrement(ref taskQueuing);
  33:                  }
  34:                  // 等待任务完成信号
  35:                  lock (semaphore)
  36:                      System.Threading.Monitor.Wait(semaphore, 1000);
  37:              }
  38:              while (true);
  39:          }
  40:   
  41:          /// <summary>
  42:          /// 等待所有任务执行完成
  43:          /// </summary>
  44:          public void WaitAllTaskCompleted()
  45:          {
  46:              while (taskQueuing > 0 && taskRunning > 0)
  47:                  lock (semaphore)
  48:                      if (taskQueuing > 0 && taskRunning > 0)
  49:                          System.Threading.Monitor.Wait(semaphore, 1000);
  50:          }
  51:   
  52:          private void RunTask(object task)
  53:          {
  54:              try
  55:              {
  56:                  System.Threading.Interlocked.Increment(ref taskRunning);
  57:                  System.Threading.Interlocked.Decrement(ref taskQueuing);
  58:                  RunTaskCore(task);
  59:              }
  60:              finally
  61:              {
  62:                  System.Threading.Interlocked.Decrement(ref taskRunning);
  63:                  // 发送任务完成信号
  64:                  lock (semaphore)
  65:                      System.Threading.Monitor.Pulse(semaphore);
  66:              }
  67:          }
  68:   
  69:          protected virtual void RunTaskCore(object task)
  70:          {
  71:              // todo : RunTaskCore
  72:          }

    比较简单,没有考虑取消等事情,另外QueueTask方法应该与WaitAllTaskCompleted方法在同一个线程中执行。

posted on 2010-06-12 12:52  Zhenway  阅读(536)  评论(0编辑  收藏  举报