### ForceStop example work loop Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control A work loop that does not include cooperative stop checks; ForceStop can still stop it via Thread.Interrupt(). ```csharp WorkID workID = powerPool.QueueWorkItem(() => { while (true) { // Do something } }); ``` -------------------------------- ### Start() Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Starts the pool, but only if PowerPoolOption.StartSuspended is set to true. ```APIDOC ## Start() ### Description Start the pool, but only if PowerPoolOption.StartSuspended is set to true. ### Method Start ### Parameters None ### Response No return value. ``` -------------------------------- ### Fetch[Async](...) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Blocks and gets the result of a work. Work ID(s) or a predicate function, CancellationToken, a flag to remove the result from storage after fetching, and a help while waiting flag can be passed as parameters. ```APIDOC ## Fetch[Async](...) ### Description Blocks and gets the result of a work. Work ID(s) or a predicate function, CancellationToken, a flag to remove the result from storage after fetching, and a help while waiting flag can be passed as parameters. ### Method Fetch or FetchAsync ### Parameters - **work ids** (optional) - Work ID(s) to fetch results from. - **predicate function** (optional) - Function to select which work result to fetch. - **CancellationToken** (optional) - Token to cancel the fetch operation. - **remove result from storage after fetch flag** (optional) - Flag indicating whether to remove the result from storage after fetching. - **help while waiting flag** (optional) - Flag indicating whether to help while waiting. ### Example ```csharp Task> resultTask = powerPool.FetchAsync(id0); ``` ``` -------------------------------- ### WorkPlacementPolicy example with WorkOption Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Divide-And-Conquer Sets PreferLocalWorker to keep work on the current worker's local queue, useful when recursively enqueuing from inside a worker. The example also enables result storage and queues a work item. ```csharp var opt = new WorkOption { ShouldStoreResult = true, WorkPlacementPolicy = WorkPlacementPolicy.PreferLocalWorker }; WorkID id = pool.QueueWorkItem(() => /* compute */, opt); ``` -------------------------------- ### Cancel(...) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Cancels works that haven't been started. Work ID(s) can be passed as parameters. ```APIDOC ## Cancel(...) ### Description Cancels works that haven't been started. Work ID(s) can be passed as parameters. ### Method Cancel ### Parameters - **work ids** (optional) - Work ID(s) to cancel. If omitted, cancels all unstarted works. ### Example ```csharp powerPool.Cancel(); ``` ``` -------------------------------- ### Other Methods Source: https://github.com/zjzmisaka/powerthreadpool/wiki/PowerPool Provides methods to start the thread pool, clear result storage, and dispose of resources. ```APIDOC ## Other Methods ### Description Provides methods to start the thread pool, clear result storage, and dispose of resources. ### Method C# methods ### Endpoint `void Start()` `void ClearResultStorage()` `void ClearResultStorage(WorkID workID)` `void ClearResultStorage(IEnumerable workIDList)` `void Dispose()` ### Parameters #### Parameters - **workID** (WorkID) - Optional - The work ID whose result storage to clear. - **workIDList** (IEnumerable) - Optional - A list of work IDs whose result storage to clear. ### Response #### Return Value - **void** - No return value. ``` -------------------------------- ### Resume(...) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Resumes the pool or specific works. Work ID(s) can be passed as parameters to resume specific works. ```APIDOC ## Resume(...) ### Description Resumes the pool or specific works. Work ID(s) can be passed as parameters to resume specific works. ### Method Resume ### Parameters - **work ids** (optional) - Work ID(s) to resume. If omitted, resumes the entire pool. ### Example ```csharp powerPool.Resume(); powerPool.Resume(id1); ``` ``` -------------------------------- ### Wait[Async](...) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Blocks and waits for the pool or specific works to complete. Work ID(s), CancellationToken, and a help while waiting flag can be passed as parameters. ```APIDOC ## Wait[Async](...) ### Description Blocks and waits for the pool or specific works to complete. Work ID(s), CancellationToken, and a help while waiting flag can be passed as parameters. ### Method Wait or WaitAsync ### Parameters - **work ids** (optional) - Work ID(s) to wait for. If omitted, waits for the entire pool. - **CancellationToken** (optional) - Token to cancel the wait operation. - **help while waiting flag** (optional) - Flag indicating whether to help while waiting. ### Example ```csharp powerPool.Wait(); powerPool.Wait(id1); ``` ``` -------------------------------- ### Fetch results by work ID or predicate Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Blocking retrieval of work results. Fetch(workID) or Fetch(workIDList) waits for completion; Fetch(predicate) filters existing results without blocking. Use FetchAsync for non-blocking retrieval. ```csharp powerPool.Fetch(workID); powerPool.Fetch(workIDList); powerPool.Fetch(x => x.Result >= 3); ``` -------------------------------- ### Cancel Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Cancels works that have not been started. Can cancel all pending works or specific work IDs. ```APIDOC ## Cancel ### Description Cancels works that have not been started. Can cancel all pending works or specific work IDs. ### Method Cancel ### Parameters - **workID** (optional) - The ID of the work to cancel. - **workIDList** (optional) - A list of work IDs to cancel. ### Example ```csharp powerPool.Cancel(); powerPool.Cancel(workID); powerPool.Cancel(workIDList); ``` ``` -------------------------------- ### For(int start, int end, Action body, int step = 1, string groupName = null) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Parallel-Execution Executes a loop in parallel from start to end, performing the specified action on each index. Supports both synchronous and asynchronous body actions. ```APIDOC ## For(int start, int end, Action body, int step = 1, string groupName = null) ### Description Executes a loop from `start` to `end` with the specified action to be performed on each index. ### Parameters - `start` (int) - Required - The start index of the loop. - `end` (int) - Required - The end index of the loop. - `body` (Action or Func) - Required - The action to execute for each loop iteration. - `step` (int) - Optional - The step value for each loop iteration. Default is 1. - `groupName` (string) - Optional - The optional name for the group. Default is null. ### Returns - Group object ### Request Example ```csharp // Do something before loop powerPool.For(0, 10, (i) => DoSomething(i)).Wait(); powerPool.For(0, 10, async (i) => await DoSomething(i)).Wait(); // Do something after loop ``` ``` -------------------------------- ### Control pool and individual work items with Pause, Resume, Stop, Wait, FetchAsync Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Shows how to queue a work item that checks pause and stop requests, then control the pool and a specific work ID. Uses PauseIfRequested, IsStopRequested, FetchAsync, Pause, Resume, Stop, and Wait. The first work item returns true when stop is requested; the second uses StopIfRequested. ```csharp PowerPool powerPool = new PowerPool(); WorkID id0 = powerPool.QueueWorkItem(() => { while (true) { powerPool.PauseIfRequested(); if (powerPool.IsStopRequested()) { return true; } // Do something } }); Task> resultTask = powerPool.FetchAsync(id0); powerPool.Pause(); powerPool.Resume(); powerPool.Stop(); powerPool.Wait(); ExecuteResult result = await resultTask; WorkID id1 = powerPool.QueueWorkItem(() => { while (true) { powerPool.PauseIfRequested(); powerPool.StopIfRequested(); // Do something } }); powerPool.Pause(id1); powerPool.Resume(id1); powerPool.Stop(id1); powerPool.Wait(id1); ``` -------------------------------- ### ClearResultStorage Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Clears the saved execution results. Can clear all results, or results for specific work IDs. ```APIDOC ## ClearResultStorage ### Description Clears the saved execution results. Can clear all results, or results for specific work IDs. ### Method ClearResultStorage ### Parameters - **workID** (optional) - The ID of the work whose result to clear. - **workIDList** (optional) - A list of work IDs whose results to clear. ### Example ```csharp powerPool.ClearResultStorage(); powerPool.ClearResultStorage(workID); powerPool.ClearResultStorage(workIDList); ``` ``` -------------------------------- ### Pause, Resume, and Stop overloads Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Call Pause, Resume, or Stop with no argument for pool-wide control, or with a work ID or list of work IDs to target specific works. ```csharp powerPool.Pause(); powerPool.Pause(workID); powerPool.Pause(workIDList); powerPool.Resume(); powerPool.Resume(workID); powerPool.Resume(workIDList); powerPool.Stop(); powerPool.Stop(workID); powerPool.Stop(workIDList); ``` -------------------------------- ### StopIfRequested with beforeStop callback Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Use the beforeStop parameter to perform cleanup or prevent stopping. Return true to continue stopping, false to cancel the stop request. ```csharp WorkID workID = powerPool.QueueWorkItem(() => { while (true) { powerPool.PauseIfRequested(); powerPool.StopIfRequested(() => { // Do something before return if (/* You want to continue stopping */) { return true; } else { return false; } }); // Do something } }); ``` -------------------------------- ### Wait for all or specific works Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Blocks the calling thread until all works terminate, or until the work(s) identified by workID or workIDList complete. Use WaitAsync for non-blocking behavior. ```csharp powerPool.Wait(); powerPool.Wait(workID); powerPool.Wait(workIDList); ``` -------------------------------- ### ForceStop(...) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Force stops the pool or specific works. Work ID(s) can be passed as parameters to force stop specific works. ```APIDOC ## ForceStop(...) ### Description Force stops the pool or specific works. Work ID(s) can be passed as parameters to force stop specific works. ### Method ForceStop ### Parameters - **work ids** (optional) - Work ID(s) to force stop. If omitted, force stops the entire pool. ### Example ```csharp powerPool.ForceStop(); ``` ``` -------------------------------- ### For Source: https://github.com/zjzmisaka/powerthreadpool/wiki/PowerPool Executes a loop that iterates from a start index to an end index, invoking the provided body action or function for each iteration. Supports synchronous and asynchronous bodies, optional step size, and optional group name. ```APIDOC ## For ### Description Executes a loop that iterates from a start index to an end index, invoking the provided body action or function for each iteration. Supports synchronous and asynchronous bodies, optional step size, and optional group name. ### Method C# method ### Endpoint `Group For(int start, int end, Action body, int step = 1, string groupName = null)` `Group For(int start, int end, Func body, int step = 1, string groupName = null)` `Group For(int start, int end, IList source, Action body, int step = 1, string groupName = null)` `Group For(int start, int end, IList source, Func body, int step = 1, string groupName = null)` `Group For(int start, int end, IList source, Action body, int step = 1, string groupName = null)` `Group For(int start, int end, IList source, Func body, int step = 1, string groupName = null)` ### Parameters #### Parameters - **start** (int) - Required - The starting index of the loop. - **end** (int) - Required - The ending index of the loop (exclusive). - **source** (IList) - Optional - A list of items to iterate over. - **body** (Action or Func or Action or Func or Action or Func) - Required - The action or function to execute for each iteration. - **step** (int) - Optional - The increment value for each iteration. Default is 1. - **groupName** (string) - Optional - The name of the group to associate with the loop. ### Response #### Return Value - **Group** - The group object representing the loop execution. ``` -------------------------------- ### Wait Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Blocks the calling thread until all works terminate, or until the specified work(s) complete. The asynchronous counterpart is WaitAsync. ```APIDOC ## Wait ### Description Blocks the calling thread until all works terminate, or until the specified work(s) complete. ### Method Wait ### Parameters - **workID** (optional) - The ID of the work to wait for. - **workIDList** (optional) - A list of work IDs to wait for. ### Example ```csharp powerPool.Wait(); powerPool.Wait(workID); powerPool.Wait(workIDList); ``` ``` -------------------------------- ### Cooperative Pause and Stop with PauseIfRequested and StopIfRequested Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Insert PauseIfRequested() and StopIfRequested() inside work logic to cooperatively pause or stop at desired positions. StopIfRequested throws WorkStopException to exit; do not catch it. Specifying a work ID ensures other works are unaffected. ```csharp WorkID workID = powerPool.QueueWorkItem(() => { while (true) { powerPool.PauseIfRequested(); powerPool.StopIfRequested(); // Do something } }); ``` -------------------------------- ### Clear results with Fetch optional parameter Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Passing true as the optional parameter to Fetch clears the execution result of the corresponding work when Fetch is called. ```csharp powerPool.Fetch(workID, true); powerPool.Fetch(workIDList, true); ``` -------------------------------- ### Pause(...) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Pauses the pool or specific works. Work ID(s) can be passed as parameters to pause specific works. ```APIDOC ## Pause(...) ### Description Pauses the pool or specific works. Work ID(s) can be passed as parameters to pause specific works. ### Method Pause ### Parameters - **work ids** (optional) - Work ID(s) to pause. If omitted, pauses the entire pool. ### Example ```csharp powerPool.Pause(); powerPool.Pause(id1); ``` ``` -------------------------------- ### PauseIfRequested[Async]() Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Inserts a pause point into the work logic. When called, the work will pause if a pause has been requested. ```APIDOC ## PauseIfRequested[Async]() ### Description Inserts a pause point into the work logic. When called, the work will pause if a pause has been requested. ### Method PauseIfRequested or PauseIfRequestedAsync ### Parameters None ### Example ```csharp powerPool.PauseIfRequested(); ``` ``` -------------------------------- ### Configure PowerPool to store results Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Sets ClearResultStorageWhenPoolStarts to true so saved execution results are cleared when the thread pool enters the running state again. By default, results are not stored to prevent memory leaks. ```csharp PowerPool powerPool = new PowerPool(new PowerPoolOption() { ClearResultStorageWhenPoolStarts = true }); ``` -------------------------------- ### Stop(...) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Stops the pool or specific works. Work ID(s) can be passed as parameters to stop specific works. ```APIDOC ## Stop(...) ### Description Stops the pool or specific works. Work ID(s) can be passed as parameters to stop specific works. ### Method Stop ### Parameters - **work ids** (optional) - Work ID(s) to stop. If omitted, stops the entire pool. ### Example ```csharp powerPool.Stop(); powerPool.Stop(id1); ``` ``` -------------------------------- ### ForceStop overloads Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control ForceStop stops the thread even without cooperative checks by calling Thread.Interrupt(). Avoid using force stop as much as possible; stopped threads are destroyed and not preserved. ```csharp powerPool.ForceStop(); powerPool.ForceStop(workID); powerPool.ForceStop(workIDList); ``` -------------------------------- ### Clear saved results directly Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Call ClearResultStorage to clear all saved results, or specify workID or workIDList to clear only those results. ```csharp powerPool.ClearResultStorage(); powerPool.ClearResultStorage(workID); powerPool.ClearResultStorage(workIDList); ``` -------------------------------- ### IsStopRequested for manual stop handling Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Check IsStopRequested() to perform pre-operations and exit safely. Stopping this way does not trigger the WorkStopped event; the work is regarded as completed normally. ```csharp WorkID workID = powerPool.QueueWorkItem(() => { while (true) { if (powerPool.IsStopRequested()) { // Do something before return return; } // Do something } }); ``` -------------------------------- ### Run a simple work with PowerPool Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Home Shows the out-of-the-box usage of PowerPool for simple synchronous and asynchronous work items. No configuration is required; just create a PowerPool and call QueueWorkItem with a lambda. ```csharp PowerPool powerPool = new PowerPool(); // Sync powerPool.QueueWorkItem(() => { // Do something }); // Async powerPool.QueueWorkItem(async () => { // Do something // await ...; }); ``` -------------------------------- ### QueueWorkItem with WorkOption Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Home Shows how to pass a WorkOption to customize the behavior of the work for both synchronous and asynchronous work items. ```csharp PowerPool powerPool = new PowerPool(new PowerPoolOption() { /* Some options */ }); // Sync powerPool.QueueWorkItem(() => { // Do something return result; }, new WorkOption() { // Some options }); // Async powerPool.QueueWorkItem(async () => { // Do something // await ...; }, new WorkOption() { // Some options }); ``` -------------------------------- ### Build with PowerShell script Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Home Run the build script with a specified version parameter. Replace {Version} with the desired version number. ```powershell powershell -File build.ps1 -Version {Version} ``` -------------------------------- ### Cancel works Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Cancels works that have not started. Use workID or workIDList to cancel specific works without affecting others. ```csharp powerPool.Cancel(); powerPool.Cancel(workID); powerPool.Cancel(workIDList); ``` -------------------------------- ### For(int start, int end, Action body, int step = 1, string groupName = null) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Creates a parallel loop that executes iterations from start to end. Returns a group object. ```APIDOC ## For(int start, int end, Action body, int step = 1, string groupName = null) ### Description Creates a parallel loop that executes iterations from start to end. ### Method For ### Parameters - **start** (int) - Required - The starting index of the loop. - **end** (int) - Required - The ending index of the loop (exclusive). - **body** (Action) - Required - The action to execute for each iteration. - **step** (int) - Optional - The step increment. Default is 1. - **groupName** (string) - Optional - The name of the group to associate with the loop. ### Response - **Group** - Returns a group object. ``` -------------------------------- ### For(int start, int end, Func body, int step = 1, string groupName = null) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Creates a parallel loop that executes iterations from start to end asynchronously. Returns a group object. ```APIDOC ## For(int start, int end, Func body, int step = 1, string groupName = null) ### Description Creates a parallel loop that executes iterations from start to end. ### Method For ### Parameters - **start** (int) - Required - The starting index of the loop. - **end** (int) - Required - The ending index of the loop (exclusive). - **body** (Func) - Required - The asynchronous action to execute for each iteration. - **step** (int) - Optional - The step increment. Default is 1. - **groupName** (string) - Optional - The name of the group to associate with the loop. ### Response - **Group** - Returns a group object. ``` -------------------------------- ### Split-one-branch-async, compute-one-branch-inline, then Fetch with help Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Divide-And-Conquer Template for top-down D&C: enqueue one recursive branch, compute the other inline, then fetch the result with helpWhileWaiting. Uses WorkOption with ShouldStoreResult and WorkPlacementPolicy.PreferLocalWorker. ```csharp long Solve(int l, int r) { if (r - l + 1 <= cutoff) return ComputeDirect(l, r); int m = (l + r) >> 1; var opt = new WorkOption { ShouldStoreResult = true, WorkPlacementPolicy = WorkPlacementPolicy.PreferLocalWorker }; // Enqueue one side WorkID rightId = pool.QueueWorkItem(() => Solve(m + 1, r), opt); // Compute the other side inline long left = Solve(l, m); // Fetch result and help while waiting long right = pool.Fetch(rightId, removeAfterFetch: false, helpWhileWaiting: true).Result; return left + right; } ``` -------------------------------- ### GetGroup() Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Gets the group object. ```APIDOC ## GetGroup() ### Description Get group object. ### Method GetGroup ### Parameters None ### Response - **Group** - Returns the group object. ``` -------------------------------- ### Cancel() Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Cancels all works that have not started running. ```APIDOC ## Cancel() ### Description Cancel all works that have not started running. ### Method Cancel ### Parameters None ### Response No return value. ``` -------------------------------- ### For(int start, int end, IList source, Action body, int step = 1, string groupName = null) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Creates a parallel loop that executes iterations from start to end over a source list. Returns a group object. ```APIDOC ## For(int start, int end, IList source, Action body, int step = 1, string groupName = null) ### Description Creates a parallel loop that executes iterations from start to end. ### Method For ### Parameters - **start** (int) - Required - The starting index of the loop. - **end** (int) - Required - The ending index of the loop (exclusive). - **source** (IList) - Required - The source list to iterate over. - **body** (Action) - Required - The action to execute for each element. - **step** (int) - Optional - The step increment. Default is 1. - **groupName** (string) - Optional - The name of the group to associate with the loop. ### Response - **Group** - Returns a group object. ``` -------------------------------- ### QueueWorkItem method signatures reference Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Home Lists the supported overloads of QueueWorkItem for both synchronous and asynchronous work items. Up to 5 type parameters are supported; the wildcard * accepts a WorkOption or callback, and ? is a CancellationToken that receives stop notifications. ```csharp // Sync WorkID QueueWorkItem(Action action, T1 param1, ..., *); WorkID QueueWorkItem(Action action, *); WorkID QueueWorkItem(Action action, object[] param, *); WorkID QueueWorkItem(Func function, T1 param1, ..., *); WorkID QueueWorkItem(Func function, *); WorkID QueueWorkItem(Func function, object[] param, *); // Async WorkID QueueWorkItem(Func asyncFunc, T1 param1, ..., _, *); WorkID QueueWorkItem(Func asyncFunc, _, *); WorkID QueueWorkItem(Func asyncFunc, object[] param, _, *); WorkID QueueWorkItem(Func> asyncFunc, T1 param1, ..., _, *); WorkID QueueWorkItem(Func> asyncFunc, _, *); WorkID QueueWorkItem(Func> asyncFunc, object[] param, _, *); ``` -------------------------------- ### PoolStarted Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Events This event is triggered when the thread pool is started. ```APIDOC ## PoolStarted ### Description This event is triggered when the thread pool is started. ### Event Signature ```csharp event EventHandler PoolStarted; ``` ``` -------------------------------- ### For(int start, int end, IList source, Action body, int step = 1, string groupName = null) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Creates a parallel loop that executes iterations from start to end over a source list with index. Returns a group object. ```APIDOC ## For(int start, int end, IList source, Action body, int step = 1, string groupName = null) ### Description Creates a parallel loop that executes iterations from start to end. ### Method For ### Parameters - **start** (int) - Required - The starting index of the loop. - **end** (int) - Required - The ending index of the loop (exclusive). - **source** (IList) - Required - The source list to iterate over. - **body** (Action) - Required - The action to execute for each element, with the element and its index. - **step** (int) - Optional - The step increment. Default is 1. - **groupName** (string) - Optional - The name of the group to associate with the loop. ### Response - **Group** - Returns a group object. ``` -------------------------------- ### Minimal D&C configuration with PowerPoolOption Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Divide-And-Conquer Use for most divide-and-conquer workloads. Deque queueing favors depth-first execution, and single-item stealing reduces cache thrash and mitigates task ping-pong. ```csharp PowerPoolOption options = new PowerPoolOption { QueueType = QueueType.Deque, StealOneWorkOnly = true, }; ``` -------------------------------- ### For(int start, int end, IList source, Func body, int step = 1, string groupName = null) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Creates a parallel loop that executes iterations from start to end over a source list asynchronously. Returns a group object. ```APIDOC ## For(int start, int end, IList source, Func body, int step = 1, string groupName = null) ### Description Creates a parallel loop that executes iterations from start to end. ### Method For ### Parameters - **start** (int) - Required - The starting index of the loop. - **end** (int) - Required - The ending index of the loop (exclusive). - **source** (IList) - Required - The source list to iterate over. - **body** (Func) - Required - The asynchronous action to execute for each element. - **step** (int) - Optional - The step increment. Default is 1. - **groupName** (string) - Optional - The name of the group to associate with the loop. ### Response - **Group** - Returns a group object. ``` -------------------------------- ### For(int start, int end, IList source, Action body, int step = 1, string groupName = null) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Parallel-Execution Executes a loop in parallel over a collection from start to end, performing the specified action on each element. Supports both synchronous and asynchronous body actions. ```APIDOC ## For(int start, int end, IList source, Action body, int step = 1, string groupName = null) ### Description Executes a loop over a collection from `start` to `end`, performing the specified action on each element. ### Parameters - `start` (int) - Required - The start index of the loop. - `end` (int) - Required - The end index of the loop. - `source` (IList) - Required - The source collection of elements to be processed in the loop. - `body` (Action or Func) - Required - The action to execute for each loop iteration. - `step` (int) - Optional - The step value for each loop iteration. Default is 1. - `groupName` (string) - Optional - The optional name for the group. Default is null. ### Returns - Group object ### Request Example ```csharp // Do something before loop powerPool.For(0, 10, list, (item) => DoSomething(item)).Wait(); powerPool.For(0, 10, list, async (item) => await DoSomething(item)).Wait(); // Do something after loop ``` ``` -------------------------------- ### Wait and Fetch with helpWhileWaiting Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Divide-And-Conquer Use helpWhileWaiting: true to let the calling thread execute available work while blocked, reducing idle time. Shown for pool.Wait and pool.Fetch with removeAfterFetch: false. ```csharp // Wait for the entire pool to finish while helping: pool.Wait(helpWhileWaiting: true); // Fetch a result while helping: var res = pool.Fetch(someId, removeAfterFetch: false, helpWhileWaiting: true); long value = res.Result; ``` -------------------------------- ### GetGroupMemberSet() Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Gets all members of a group as a list of work IDs. ```APIDOC ## GetGroupMemberSet() ### Description Get all members of a group. ### Method GetGroupMemberSet ### Parameters None ### Response - **IEnumerable** - Returns a list of work IDs that are members of the group. ``` -------------------------------- ### For(int start, int end, IList source, Func body, int step = 1, string groupName = null) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Creates a parallel loop that executes iterations from start to end over a source list with index asynchronously. Returns a group object. ```APIDOC ## For(int start, int end, IList source, Func body, int step = 1, string groupName = null) ### Description Creates a parallel loop that executes iterations from start to end. ### Method For ### Parameters - **start** (int) - Required - The starting index of the loop. - **end** (int) - Required - The ending index of the loop (exclusive). - **source** (IList) - Required - The source list to iterate over. - **body** (Func) - Required - The asynchronous action to execute for each element, with the element and its index. - **step** (int) - Optional - The step increment. Default is 1. - **groupName** (string) - Optional - The name of the group to associate with the loop. ### Response - **Group** - Returns a group object. ``` -------------------------------- ### For(int start, int end, IList source, Action body, int step = 1, string groupName = null) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Parallel-Execution Executes a loop in parallel over a collection from start to end, performing the specified action on each element and its index. Supports both synchronous and asynchronous body actions. ```APIDOC ## For(int start, int end, IList source, Action body, int step = 1, string groupName = null) ### Description Executes a loop over a collection from `start` to `end`, performing the specified action on each element and its index. ### Parameters - `start` (int) - Required - The start index of the loop. - `end` (int) - Required - The end index of the loop. - `source` (IList) - Required - The source collection of elements to be processed in the loop. - `body` (Action or Func) - Required - The action to execute for each loop iteration, receiving an element from the source collection and the iteration index. - `step` (int) - Optional - The step value for each loop iteration. Default is 1. - `groupName` (string) - Optional - The optional name for the group. Default is null. ### Returns - Group object ### Request Example ```csharp // Do something before loop powerPool.For(0, 10, list, (item, i) => DoSomething(item, i)).Wait(); powerPool.For(0, 10, list, async(item, i) => await DoSomething(item, i)).Wait(); // Do something after loop ``` ``` -------------------------------- ### BenchmarkTotalExecutionTimeOfAllPriorityWork Benchmark Output Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Sync-Async BenchmarkDotNet output for total completion time of 600 tasks (50 low, then 200 each of low, medium, high). Shows all four methods have similar mean times (~986 ms) and allocation ratios; TestPowerThreadPool has the highest allocation (1.95 MB). ```text BenchmarkDotNet v0.14.0, Windows 11 (10.0.26100.33296) (Hyper-V) Unknown processor .NET SDK 10.0.401 [Host] : .NET 8.0.30 (8.0.3026.36720), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI Job-CDYJCI : .NET 8.0.30 (8.0.3026.36720), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI InvocationCount=1 UnrollFactor=1 | Method | Mean | Error | StdDev | Ratio | Allocated | Alloc Ratio | |------------------------------------------ |---------:|--------:|--------:|------:|----------:|------------:| | TestPriorityNotPropagatedThreadStaticSeed | 985.9 ms | 0.26 ms | 0.20 ms | 1.00 | 1.56 MB | 0.80 | | TestPriorityPropagatedViaPerPriorityLane | 989.4 ms | 0.51 ms | 0.40 ms | 1.00 | 1.69 MB | 0.87 | | TestPriorityPropagatedViaSyncContext | 985.5 ms | 1.23 ms | 1.02 ms | 1.00 | 1.6 MB | 0.82 | | TestPowerThreadPool | 986.0 ms | 0.31 ms | 0.26 ms | 1.00 | 1.95 MB | 1.00 | ``` -------------------------------- ### Group Name property Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Group Gets the group name. This property is read-only. ```csharp string Name; ``` -------------------------------- ### QueueWorkItem (Async with five parameters) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/PowerPool Queues an asynchronous work item that takes five parameters of types T1, T2, T3, T4, and T5 and returns a result. Provides an out task to await the execution result and an optional callback. ```APIDOC ## QueueWorkItem(Func>, T1, T2, T3, T4, T5, out Task>, Action>) ### Description Queues an asynchronous work item that accepts five parameters of types T1, T2, T3, T4, and T5 and returns a result. The method provides an out task to await the execution result and an optional callback for completion notification. ### Method QueueWorkItem ### Parameters - **asyncFunc** (Func>) - Required - The asynchronous function to execute. - **param1** (T1) - Required - The first parameter to pass to the async function. - **param2** (T2) - Required - The second parameter to pass to the async function. - **param3** (T3) - Required - The third parameter to pass to the async function. - **param4** (T4) - Required - The fourth parameter to pass to the async function. - **param5** (T5) - Required - The fifth parameter to pass to the async function. - **task** (out Task>) - Required - The task representing the execution result. - **callBack** (Action>) - Optional - Callback invoked upon completion. ### Returns WorkID - The identifier of the queued work item. ``` ```APIDOC ## QueueWorkItem(Func>, T1, T2, T3, T4, T5, out Task>, WorkOption) ### Description Queues an asynchronous work item that accepts five parameters of types T1, T2, T3, T4, and T5 and returns a result. Allows specifying work options for execution. ### Method QueueWorkItem ### Parameters - **asyncFunc** (Func>) - Required - The asynchronous function to execute. - **param1** (T1) - Required - The first parameter to pass to the async function. - **param2** (T2) - Required - The second parameter to pass to the async function. - **param3** (T3) - Required - The third parameter to pass to the async function. - **param4** (T4) - Required - The fourth parameter to pass to the async function. - **param5** (T5) - Required - The fifth parameter to pass to the async function. - **task** (out Task>) - Required - The task representing the execution result. - **option** (WorkOption) - Required - Options for the work item execution. ### Returns WorkID - The identifier of the queued work item. ``` -------------------------------- ### Interval Property Source: https://github.com/zjzmisaka/powerthreadpool/wiki/RunningTimerOption Gets or sets the time, in milliseconds, between events for the running timer. ```APIDOC ## Interval Property ### Description The time, in milliseconds, between events. ### Property Signature ```csharp double Interval; ``` ### Type - **double** - The interval in milliseconds. ``` -------------------------------- ### Resume (overloads) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/PowerPool Resumes the entire pool or specific work items. Overloads allow resuming by ID or by list, and optionally resume work paused by ID. ```APIDOC ## Resume (overloads) ### Description Resumes the entire pool or specific work items. Overloads allow resuming by ID or by list, and optionally resume work paused by ID. ### Method void Resume(bool resumeWorkPausedByID = false); bool Resume(WorkID id); List Resume(IEnumerable idList); ### Parameters - **resumeWorkPausedByID** (bool) - Optional - If true, also resumes work items that were paused by ID. - **id** (WorkID) - Optional - The ID of the work item to resume. - **idList** (IEnumerable) - Optional - A collection of work item IDs to resume. ### Response - **void** - No return value for the parameterless overload. - **bool** - Returns true if the resume was successful; otherwise, false. - **List** - Returns the list of work IDs that were successfully resumed. ``` -------------------------------- ### Group MemberCount property Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Group Gets the total number of members in the group. This property is read-only. ```csharp int MemberCount; ``` -------------------------------- ### QueueWorkItem with callback Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Home Shows how to pass a callback to QueueWorkItem for both synchronous and asynchronous work items. The callback receives the result of the work. ```csharp PowerPool powerPool = new PowerPool(new PowerPoolOption() { /* Some options */ }); // Sync powerPool.QueueWorkItem(() => { // Do something return result; }, (res) => { // Callback of the work }); // Async powerPool.QueueWorkItem(async () => { // Do something // await ...; }, (res) => { // Callback of the work }); ``` -------------------------------- ### Cancel(WorkID id) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/API-Summary Cancels a specific work by ID if it has not started running. Returns a boolean indicating success. ```APIDOC ## Cancel(WorkID id) ### Description Cancel the work by id if the work has not started running. Returns is succeed. ### Method Cancel ### Parameters - **id** (WorkID) - Required - The work ID to cancel. ### Response - **bool** - Returns true if the cancellation succeeded, otherwise false. ``` -------------------------------- ### QueueWorkItem (with WorkOption) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/PowerPool Queues an asynchronous work item that accepts two parameters and returns a result. The method returns a WorkID and provides a task to await the execution result. ```APIDOC ## QueueWorkItem(Func>, T1, T2, out Task>, WorkOption) ### Description Queues an asynchronous work item that accepts two parameters and returns a result. The method returns a WorkID and provides a task to await the execution result. ### Method QueueWorkItem ### Signature WorkID QueueWorkItem(Func> asyncFunc, T1 param1, T2 param2, out Task> task, WorkOption option); ### Parameters - **asyncFunc** (Func>) - Required - The asynchronous function to execute. - **param1** (T1) - Required - First parameter passed to the async function. - **param2** (T2) - Required - Second parameter passed to the async function. - **task** (out Task>) - Required - Output task that completes with the execution result. - **option** (WorkOption) - Required - Work option controlling execution behavior. ### Returns - **WorkID** - Identifier for the queued work item. ``` -------------------------------- ### Group MemberSet property Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Group Gets the set of work IDs that are current members of the group. This property is read-only. ```csharp ConcurrentSet MemberSet; ``` -------------------------------- ### IsStopRequested() Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Inserts a check point into the work logic to see if a stop has been requested by calling Stop(...). ```APIDOC ## IsStopRequested() ### Description Inserts a check point into the work logic to see if a stop has been requested by calling Stop(...). ### Method IsStopRequested ### Parameters None ### Example ```csharp if (powerPool.IsStopRequested()) { return true; } ``` ``` -------------------------------- ### StopIfRequested(...) Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Work-Control Inserts a stop point into the work logic. A function that is executed before the stop process can be passed as a parameter. ```APIDOC ## StopIfRequested(...) ### Description Inserts a stop point into the work logic. A function that is executed before the stop process can be passed as a parameter. ### Method StopIfRequested ### Parameters - **function that is executed before the stop process** (optional) - A function to execute before stopping. ### Example ```csharp powerPool.StopIfRequested(); ``` ``` -------------------------------- ### For with Action and async body Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Parallel-Execution Executes a parallel loop from start to end with a synchronous or asynchronous body. Use .Wait() to block until completion. ```csharp // Do something before loop powerPool.For(0, 10, (i) => DoSomething(i)).Wait(); powerPool.For(0, 10, async (i) => await DoSomething(i)).Wait(); // Do something after loop ``` -------------------------------- ### IStealablePriorityCollection Get method Source: https://github.com/zjzmisaka/powerthreadpool/wiki/Queue-Type Retrieves and removes the highest priority item. Typically called by the owner thread to fetch the next work. ```csharp T Get(); ```