/// <summary> /// 开启或唤醒一个线程去执行指定的回调方法 /// </summary> /// <param name="cb">回调函数</param> /// <param name="arg">回调函数参数对象</param> public static void QueueUserWorkItem(WaitCallback cb, Object arg) { //剔除无效线程,保持一定个数的空闲线程 Monitor.Enter(mythreads); for (int i = mythreads.Count, len = minWorkerThreads; i < len; i++) { mythreads.Add(new myThread()); } int sum = 0; for (int i = mythreads.Count - 1; i > -1; i--) { myThread td = mythreads[i]; if (td.IsWait) { sum++; } if (sum <= maxWorkerThreads) { continue; } if (!td.IsEffect()) { mythreads.RemoveAt(i); td.Close(); } } myThread[] thds = mythreads.ToArray(); Monitor.PulseAll(mythreads); Monitor.Exit(mythreads); //从池内找出空闲线程执行 foreach (myThread thd in thds) { if (!thd.IsWait) { continue; } thd.Start(cb, arg); return; } Monitor.Enter(mythreads); myThread t = new myThread(); mythreads.Add(t); Monitor.PulseAll(mythreads); Monitor.Exit(mythreads); t.Start(cb, arg); }
/// <summary> /// 开启或唤醒一个线程去执行指定的回调方法 /// </summary> /// <param name="cb">回调函数</param> /// <param name="arg">回调函数参数对象</param> public static void QueueUserWorkItem(WaitCallback cb, Object arg) { //剔除无效线程,保持一定个数的空闲线程 Monitor.Enter(mythreads); for (int i = mythreads.Count, len = minWorkerThreads; i < len; i++) { mythreads.Add(new myThread()); } int sum = 0; for (int i = mythreads.Count - 1; i > -1; i--) { myThread td = mythreads[i]; if (td.IsEnd) { mythreads.RemoveAt(i); td.Close(); Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 关闭线程"); myLog.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 关闭线程"); continue; } if (td.IsWait) { sum++; } if (sum <= maxWorkerThreads) { continue; } if (!td.IsEffect()) { mythreads.RemoveAt(i); td.Close(); Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 关闭线程"); myLog.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 关闭线程"); } } myThread[] thds = mythreads.ToArray(); Monitor.PulseAll(mythreads); Monitor.Exit(mythreads); //从池内找出空闲线程执行 foreach (myThread thd in thds) { if (!thd.IsWait) { continue; } thd.Start(cb, arg); return; } string strsum = Convert.ToString(thds.Length + 1); Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 新线程: " + strsum); myLog.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " 新线程: " + strsum); Monitor.Enter(mythreads); myThread t = new myThread(); mythreads.Add(t); Monitor.PulseAll(mythreads); Monitor.Exit(mythreads); try { t.Start(cb, arg); } catch (Exception ex) { if (ex is OutOfMemoryException) { isResetNeed = true; } NameValueCollection attr = new NameValueCollection(); attr["进程数"] = strsum; ExceptionManager.Publish(ex, attr); throw ex; } }