Beispiel #1
0
 /// <summary>
 /// 线程工作执行完成后执行回调方法
 /// </summary>
 /// <param name="thread">当前执行线程</param>
 public void WorkComplete(ThreadExtend <T> thread)
 {
     lock (obj)
     {
         if (taskQueue.Count() > 0)
         {
             HandlerItem <T> taskItem = taskQueue.Dequeue();
             thread.SetWorkTask(taskItem);
             thread.StartThread();
         }
         else
         {
             workThread.Remove(thread.Key);
             if (freeThread.Count() >= min)
             {
                 allThread.Remove(thread.Key);
                 thread.Close();
                 thread.Dispose();
             }
             else
             {
                 thread.SetWorkTask(null);
                 freeThread.Enqueue(thread);
             }
             if (!workThread.Any())
             {
                 Dispose();
             }
         }
     }
 }
Beispiel #2
0
        /// <summary>
        /// 开启线程池
        /// </summary>
        public void Start()
        {
            if (min <= 0 || max <= 0 || min > max)
            {
                throw new Exception("参数设置异常,必须正确设置初始线程数、最大线程数,或者使用默认设置");
            }
            allThread  = new Dictionary <string, ThreadExtend <T> >();
            workThread = new Dictionary <string, ThreadExtend <T> >();
            freeThread = new Queue <ThreadExtend <T> >();
            ThreadExtend <T> thread = null;

            for (int i = 0; i < min; i++)
            {
                index++;
                thread = new ThreadExtend <T>(index);
                thread.WorkComplete += new Action <ThreadExtend <T> >(WorkComplete);
                allThread.Add(thread.Key, thread);
                freeThread.Enqueue(thread);
            }
            if (!isOpenThread)
            {
                isOpenThread = true;
                RealStartThread();
            }
        }
Beispiel #3
0
        /// <summary>
        /// 开启线程(总线程不能大于最大线程数)
        /// </summary>
        /// <param name="count">要开启的线程数</param>
        /// <param name="threadCount">已有线程数量</param>
        private void OpenThread(int count, int threadCount)
        {
            ThreadExtend <T> thread = null;

            //增量创建线程
            for (int i = 0; i < count; i++)
            {
                if ((threadCount + i) < max)
                {
                    index++;
                    thread = new ThreadExtend <T>(index);
                    thread.WorkComplete += new Action <ThreadExtend <T> >(WorkComplete);
                    allThread.Add(thread.Key, thread);
                    freeThread.Enqueue(thread);
                }
                else
                {
                    break;
                }
            }
        }