/// <summary> /// 新增工作调度 /// </summary> /// <param name="callBack">回调函数</param> /// <param name="state">调用参数</param> /// <param name="autoRun">是否立即执行</param> public void AddThreadItem(System.Threading.WaitCallback callBack, object state, bool autoRun) { lock (TaskThreadPool.lockObject) { ThreadPoolItem item = new ThreadPoolItem() { CallBack = callBack, State = state, AutoRun = autoRun }; item.Complete += new System.Threading.WaitCallback((st) => { lock (TaskThreadPool.lockObject) { this.WorkingCount--; } ThreadPoolItem tpi = st as ThreadPoolItem; if (tpi != null && !tpi.AutoRun) { if (this._waitThreadQueue.Count > 0) { ThreadPoolItem queueItem = this._waitThreadQueue.Dequeue(); this.runThreadItem(queueItem); } } }); item.Error += new System.Threading.WaitCallback((st) => { lock (TaskThreadPool.lockObject) { this.WorkingCount--; } ThreadPoolItem tpi = st as ThreadPoolItem; if (tpi != null && !tpi.AutoRun) { if (this._waitThreadQueue.Count > 0) { ThreadPoolItem queueItem = this._waitThreadQueue.Dequeue(); this.runThreadItem(queueItem); } } }); //如果直接运行,交由线程池去维护 if (autoRun && this.CanRun) { System.Threading.ThreadPool.QueueUserWorkItem((st) => { ThreadPoolItem tpi = st as ThreadPoolItem; if (tpi != null) { tpi.Run(); } }, item); } else //交由线程队列去维护 { if (!this.CanRun) { this._waitThreadQueue.Enqueue(item); } else { this.runThreadItem(item); } } } }
private void runThreadItem(ThreadPoolItem item) { lock (TaskThreadPool.lockObject) { this.WorkingCount++; } System.Threading.ThreadPool.QueueUserWorkItem((st) => { ThreadPoolItem tpi = st as ThreadPoolItem; if (tpi != null) { tpi.Run(); } }, item); }