//-- Please call this function in locked status. private static void ExitWorker(bool normal, TaskThreadPoolCore core) { if (normal) { core.normalThreadCount--; } else { core.tempThreadCount--; } if (core.normalThreadCount == 0 && core.tempThreadCount == 0 && core.stopped && core.backgroundThread == false) { core.quitSemaphore.Release(); } }
private static void Worker(Object obj) { TaskThreadPoolCore core = (TaskThreadPoolCore)obj; while (true) { ITask task = null; core.semaphore.WaitOne(); lock (core) { if (core.taskQueue.Count > 0) { task = core.taskQueue.Dequeue(); core.busyThreadCount++; } else if (core.stopped) { ExitWorker(true, core); return; } else { continue; } } try { task.Run(); } catch (Exception e) { if (core.errorRecorder != null) { core.errorRecorder.RecordError(e); } } finally { lock (core) { core.busyThreadCount--; } } } }
//----------------[ Constructor ]-----------------------// public TaskThreadPool(int initThreadCount, int perfectThreadCount, int maxThreadCount, int maxQueueLengthLimitation = 0, int tempLatencySeconds = 60, bool usingBackGroundThread = true) { if (initThreadCount < 0) { throw new ArgumentException("Param initThreadCount is less than Zero.", nameof(initThreadCount)); } if (maxThreadCount <= 0) { throw new ArgumentException("Param maxThreadCount is less than or equal to Zero.", nameof(maxThreadCount)); } if (perfectThreadCount < initThreadCount) { throw new ArgumentOutOfRangeException(nameof(perfectThreadCount), "Param perfectThreadCount is less than initThreadCount"); } if (maxThreadCount < perfectThreadCount) { throw new ArgumentOutOfRangeException(nameof(maxThreadCount), "Param maxThreadCount is less than perfectThreadCount"); } perfectCount = perfectThreadCount; maxCount = maxThreadCount; maxQueueLength = maxQueueLengthLimitation; core = new TaskThreadPoolCore(tempLatencySeconds, usingBackGroundThread); for (int i = 0; i < initThreadCount; i++) { var thread = new Thread(Worker) { Name = "FPNN.ThreadPool.NormalWorker", IsBackground = core.backgroundThread }; thread.Start(core); core.normalThreadCount++; //-- Unneed lock in there. } }
private static void TempWorker(Object obj) { TaskThreadPoolCore core = (TaskThreadPoolCore)obj; int latencySeconds = core.tempThreadLatencySeconds; DateTime idleTime = DateTime.Now; while (true) { ITask task = null; core.semaphore.WaitOne(latencySeconds * 1000); lock (core) { if (core.taskQueue.Count > 0) { task = core.taskQueue.Dequeue(); core.busyThreadCount++; } else if (core.stopped) { ExitWorker(false, core); return; } else { TimeSpan duration = DateTime.Now - idleTime; latencySeconds -= Convert.ToInt32(duration.TotalSeconds); if (latencySeconds <= 0) { ExitWorker(false, core); return; } else { continue; } } } try { task.Run(); } catch (Exception e) { if (core.errorRecorder != null) { core.errorRecorder.RecordError(e); } } finally { lock (core) { core.busyThreadCount--; } } idleTime = DateTime.Now; } }