// Get Taskpool started by kicking off some tasks /// <summary> /// Procedure gets the TaskPool started by kicking off a few /// TPTask threads. /// </summary> public static void Initialize() { if (TPTask.Tasks != 0) { return; } try { lock (lstTasks.SyncRoot) { // If shutting down then exit if (bShuttingDown) { return; } // If already initialized then exit if (bInitialized) { return; } // Hook up event handlers and flag initialized if (!bInitialized) { TPTask.TPTaskComplete += new TPTask.TPTaskCompleteHandler(OnTPTaskComplete); bInitialized = true; } for (int i = 0; i < MIN_ACTIVE_TASKS; i++) { TPTaskInit init = new TPTaskInit(); // Create new TPTask init.Task = new TPTask(ref leaderSignal, ref workSignal); // Keep thread in ThreadPool init.Task.RecycleTask = true; // Create worker thread init.Worker = new Thread(new ThreadStart(init.Task.Service)); // Start worker init.Worker.Start(); // Add this task to our list of tasks lstTasks.Add(init); } } //End-Lock on lstTasks } //End-try catch (Exception /*e*/) {} }
/// <summary> /// Procedure shuts down the TaskPool by allowing the TPTask threads /// running to finish what they are doing and exit the TaskPool(up to MAX_THREAD_WAIT) /// before aborting each one. /// </summary> /// <remarks>To shutdown the TaskPool, iterate thru the list of /// TPTasks and set their RecycleTask property to false, /// so they terminate after they finish processing their current /// request and wait (up to MAX_THREAD_WAIT) on each TPTask thread /// to exit before aborting the TPTask thread. /// </remarks> public static void Shutdown() { lock (lstTasks.SyncRoot) { // Signal that we are shutting down bShuttingDown = true; workSignal.AllowReset = false; workSignal.Signal(); for (int i = 0; i < lstTasks.Count; i++) { try { TPTaskInit init = (TPTaskInit)lstTasks[i]; // Do not recycle task init.Task.RecycleTask = false; // Wait on thread to exit. // Instead of waiting indefinitely // we may have have to interrupt it and // catch the exception init.Worker.Join(MAX_THREAD_WAIT); if (init.Worker.IsAlive) { init.Worker.Abort(); } } catch (Exception e) { string strMsg = e.Message; } } // Clear all tasks lstTasks.Clear(); // Clear all client subscriptions ClientNotification.Clear(); // Set threadpool as uninitialized bInitialized = false; } //End-lock lstTasks } //End-Shutdown