SmartThreadPool.cs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  1. #region Release History
  2. // Smart Thread Pool
  3. // 7 Aug 2004 - Initial release
  4. //
  5. // 14 Sep 2004 - Bug fixes
  6. //
  7. // 15 Oct 2004 - Added new features
  8. // - Work items return result.
  9. // - Support waiting synchronization for multiple work items.
  10. // - Work items can be cancelled.
  11. // - Passage of the caller thread’s context to the thread in the pool.
  12. // - Minimal usage of WIN32 handles.
  13. // - Minor bug fixes.
  14. //
  15. // 26 Dec 2004 - Changes:
  16. // - Removed static constructors.
  17. // - Added finalizers.
  18. // - Changed Exceptions so they are serializable.
  19. // - Fixed the bug in one of the SmartThreadPool constructors.
  20. // - Changed the SmartThreadPool.WaitAll() so it will support any number of waiters.
  21. // The SmartThreadPool.WaitAny() is still limited by the .NET Framework.
  22. // - Added PostExecute with options on which cases to call it.
  23. // - Added option to dispose of the state objects.
  24. // - Added a WaitForIdle() method that waits until the work items queue is empty.
  25. // - Added an STPStartInfo class for the initialization of the thread pool.
  26. // - Changed exception handling so if a work item throws an exception it
  27. // is rethrown at GetResult(), rather then firing an UnhandledException event.
  28. // Note that PostExecute exception are always ignored.
  29. //
  30. // 25 Mar 2005 - Changes:
  31. // - Fixed lost of work items bug
  32. //
  33. // 3 Jul 2005: Changes.
  34. // - Fixed bug where Enqueue() throws an exception because PopWaiter() returned null, hardly reconstructed.
  35. //
  36. // 16 Aug 2005: Changes.
  37. // - Fixed bug where the InUseThreads becomes negative when canceling work items.
  38. //
  39. // 31 Jan 2006 - Changes:
  40. // - Added work items priority
  41. // - Removed support of chained delegates in callbacks and post executes (nobody really use this)
  42. // - Added work items groups
  43. // - Added work items groups idle event
  44. // - Changed SmartThreadPool.WaitAll() behavior so when it gets empty array
  45. // it returns true rather then throwing an exception.
  46. // - Added option to start the STP and the WIG as suspended
  47. // - Exception behavior changed, the real exception is returned by an
  48. // inner exception
  49. // - Added performance counters
  50. // - Added priority to the threads in the pool
  51. //
  52. // 13 Feb 2006 - Changes:
  53. // - Added a call to the dispose of the Performance Counter so
  54. // their won't be a Performance Counter leak.
  55. // - Added exception catch in case the Performance Counters cannot
  56. // be created.
  57. //
  58. // 17 May 2008 - Changes:
  59. // - Changed the dispose behavior and removed the Finalizers.
  60. // - Enabled the change of the MaxThreads and MinThreads at run time.
  61. // - Enabled the change of the Concurrency of a IWorkItemsGroup at run
  62. // time If the IWorkItemsGroup is a SmartThreadPool then the Concurrency
  63. // refers to the MaxThreads.
  64. // - Improved the cancel behavior.
  65. // - Added events for thread creation and termination.
  66. // - Fixed the HttpContext context capture.
  67. // - Changed internal collections so they use generic collections
  68. // - Added IsIdle flag to the SmartThreadPool and IWorkItemsGroup
  69. // - Added support for WinCE
  70. // - Added support for Action<T> and Func<T>
  71. //
  72. // 07 April 2009 - Changes:
  73. // - Added support for Silverlight and Mono
  74. // - Added Join, Choice, and Pipe to SmartThreadPool.
  75. // - Added local performance counters (for Mono, Silverlight, and WindowsCE)
  76. // - Changed duration measures from DateTime.Now to Stopwatch.
  77. // - Queues changed from System.Collections.Queue to System.Collections.Generic.LinkedList<T>.
  78. //
  79. // 21 December 2009 - Changes:
  80. // - Added work item timeout (passive)
  81. //
  82. // 20 August 2012 - Changes:
  83. // - Added set name to threads
  84. // - Fixed the WorkItemsQueue.Dequeue.
  85. // Replaced while (!Monitor.TryEnter(this)); with lock(this) { ... }
  86. // - Fixed SmartThreadPool.Pipe
  87. // - Added IsBackground option to threads
  88. // - Added ApartmentState to threads
  89. // - Fixed thread creation when queuing many work items at the same time.
  90. //
  91. // 24 August 2012 - Changes:
  92. // - Enabled cancel abort after cancel. See: http://smartthreadpool.codeplex.com/discussions/345937 by alecswan
  93. // - Added option to set MaxStackSize of threads
  94. #endregion
  95. using System;
  96. using System.Security;
  97. using System.Threading;
  98. using System.Collections.Concurrent;
  99. using System.Collections.Generic;
  100. using System.Diagnostics;
  101. using System.Runtime.CompilerServices;
  102. using Amib.Threading.Internal;
  103. namespace Amib.Threading
  104. {
  105. #region SmartThreadPool class
  106. /// <summary>
  107. /// Smart thread pool class.
  108. /// </summary>
  109. public partial class SmartThreadPool : WorkItemsGroupBase, IDisposable
  110. {
  111. #region Public Default Constants
  112. /// <summary>
  113. /// Default minimum number of threads the thread pool contains. (0)
  114. /// </summary>
  115. public const int DefaultMinWorkerThreads = 0;
  116. /// <summary>
  117. /// Default maximum number of threads the thread pool contains. (25)
  118. /// </summary>
  119. public const int DefaultMaxWorkerThreads = 25;
  120. /// <summary>
  121. /// Default idle timeout in milliseconds. (One minute)
  122. /// </summary>
  123. public const int DefaultIdleTimeout = 60 * 1000; // One minute
  124. /// <summary>
  125. /// Indicate to copy the security context of the caller and then use it in the call. (false)
  126. /// </summary>
  127. public const bool DefaultUseCallerCallContext = false;
  128. /// <summary>
  129. /// Indicate to dispose of the state objects if they support the IDispose interface. (false)
  130. /// </summary>
  131. public const bool DefaultDisposeOfStateObjects = false;
  132. /// <summary>
  133. /// The default option to run the post execute (CallToPostExecute.Always)
  134. /// </summary>
  135. public const CallToPostExecute DefaultCallToPostExecute = CallToPostExecute.Always;
  136. /// <summary>
  137. /// The default post execute method to run. (None)
  138. /// When null it means not to call it.
  139. /// </summary>
  140. public static readonly PostExecuteWorkItemCallback DefaultPostExecuteWorkItemCallback;
  141. /// <summary>
  142. /// The default is to work on work items as soon as they arrive
  143. /// and not to wait for the start. (false)
  144. /// </summary>
  145. public const bool DefaultStartSuspended = false;
  146. /// <summary>
  147. /// The default name to use for the performance counters instance. (null)
  148. /// </summary>
  149. public static readonly string DefaultPerformanceCounterInstanceName;
  150. /// <summary>
  151. /// The default thread priority (ThreadPriority.Normal)
  152. /// </summary>
  153. public const ThreadPriority DefaultThreadPriority = ThreadPriority.Normal;
  154. /// <summary>
  155. /// The default thread pool name. (SmartThreadPool)
  156. /// </summary>
  157. public const string DefaultThreadPoolName = "SmartThreadPool";
  158. /// <summary>
  159. /// The default Max Stack Size. (SmartThreadPool)
  160. /// </summary>
  161. public static readonly int? DefaultMaxStackSize = null;
  162. /// <summary>
  163. /// The default fill state with params. (false)
  164. /// It is relevant only to QueueWorkItem of Action&lt;...&gt;/Func&lt;...&gt;
  165. /// </summary>
  166. public const bool DefaultFillStateWithArgs = false;
  167. /// <summary>
  168. /// The default thread backgroundness. (true)
  169. /// </summary>
  170. public const bool DefaultAreThreadsBackground = true;
  171. /// <summary>
  172. /// The default apartment state of a thread in the thread pool.
  173. /// The default is ApartmentState.Unknown which means the STP will not
  174. /// set the apartment of the thread. It will use the .NET default.
  175. /// </summary>
  176. public const ApartmentState DefaultApartmentState = ApartmentState.Unknown;
  177. #endregion
  178. #region Member Variables
  179. /// <summary>
  180. /// Dictionary of all the threads in the thread pool.
  181. /// </summary>
  182. private readonly ConcurrentDictionary<int, ThreadEntry> m_workerThreads = new();
  183. private readonly object m_workerThreadsLock = new();
  184. /// <summary>
  185. /// Queue of work items.
  186. /// </summary>
  187. private readonly WorkItemsQueue m_workItemsQueue = new();
  188. /// <summary>
  189. /// Count the work items handled.
  190. /// Used by the performance counter.
  191. /// </summary>
  192. private int m_workItemsProcessed;
  193. /// <summary>
  194. /// Number of threads that currently work (not idle).
  195. /// </summary>
  196. private int m_inUseWorkerThreads;
  197. /// <summary>
  198. /// Stores a copy of the original STPStartInfo.
  199. /// It is used to change the MinThread and MaxThreads
  200. /// </summary>
  201. private readonly STPStartInfo m_stpStartInfo;
  202. /// <summary>
  203. /// Total number of work items that are stored in the work items queue
  204. /// plus the work items that the threads in the pool are working on.
  205. /// </summary>
  206. private int m_currentWorkItemsCount;
  207. /// <summary>
  208. /// Signaled when the thread pool is idle, i.e. no thread is busy
  209. /// and the work items queue is empty
  210. /// </summary>
  211. private ManualResetEvent m_isIdleWaitHandle = new(true);
  212. /// <summary>
  213. /// An event to signal all the threads to quit immediately.
  214. /// </summary>
  215. private ManualResetEvent m_shuttingDownEvent = new(false);
  216. /// <summary>
  217. /// A flag to indicate if the Smart Thread Pool is now suspended.
  218. /// </summary>
  219. private bool m_isSuspended;
  220. /// <summary>
  221. /// A flag to indicate the threads to quit.
  222. /// </summary>
  223. private bool m_shutdown;
  224. /// <summary>
  225. /// Counts the threads created in the pool.
  226. /// It is used to name the threads.
  227. /// </summary>
  228. private int m_threadCounter;
  229. /// <summary>
  230. /// Indicate that the SmartThreadPool has been disposed
  231. /// </summary>
  232. private bool m_isDisposed;
  233. private static long m_lastThreadCreateTS = long.MinValue;
  234. /// <summary>
  235. /// Holds all the WorkItemsGroup instaces that have at least one
  236. /// work item int the SmartThreadPool
  237. /// This variable is used in case of Shutdown
  238. /// </summary>
  239. private readonly ConcurrentDictionary<int, WorkItemsGroup> m_workItemsGroups = new();
  240. /// <summary>
  241. /// A common object for all the work items int the STP
  242. /// so we can mark them to cancel in O(1)
  243. /// </summary>
  244. private CanceledWorkItemsGroup m_canceledSmartThreadPool = new();
  245. /// <summary>
  246. /// An event to call after a thread is created, but before
  247. /// it's first use.
  248. /// </summary>
  249. private event ThreadInitializationHandler m_onThreadInitialization;
  250. /// <summary>
  251. /// An event to call when a thread is about to exit, after
  252. /// it is no longer belong to the pool.
  253. /// </summary>
  254. private event ThreadTerminationHandler m_onThreadTermination;
  255. #endregion
  256. #region Per thread
  257. /// <summary>
  258. /// A reference to the current work item a thread from the thread pool
  259. /// is executing.
  260. /// </summary>
  261. [ThreadStatic]
  262. internal static ThreadEntry CurrentThreadEntry;
  263. #endregion
  264. #region Construction and Finalization
  265. /// <summary>
  266. /// Constructor
  267. /// </summary>
  268. public SmartThreadPool()
  269. {
  270. m_stpStartInfo = new STPStartInfo();
  271. Initialize();
  272. }
  273. /// <summary>
  274. /// Constructor
  275. /// </summary>
  276. /// <param name="idleTimeout">Idle timeout in milliseconds</param>
  277. public SmartThreadPool(int idleTimeout)
  278. {
  279. m_stpStartInfo = new STPStartInfo
  280. {
  281. IdleTimeout = idleTimeout,
  282. };
  283. Initialize();
  284. }
  285. /// <summary>
  286. /// Constructor
  287. /// </summary>
  288. /// <param name="idleTimeout">Idle timeout in milliseconds</param>
  289. /// <param name="maxWorkerThreads">Upper limit of threads in the pool</param>
  290. public SmartThreadPool(int idleTimeout, int maxWorkerThreads)
  291. {
  292. m_stpStartInfo = new STPStartInfo
  293. {
  294. IdleTimeout = idleTimeout,
  295. MaxWorkerThreads = maxWorkerThreads,
  296. };
  297. Initialize();
  298. }
  299. /// <summary>
  300. /// Constructor
  301. /// </summary>
  302. /// <param name="idleTimeout">Idle timeout in milliseconds</param>
  303. /// <param name="maxWorkerThreads">Upper limit of threads in the pool</param>
  304. /// <param name="minWorkerThreads">Lower limit of threads in the pool</param>
  305. public SmartThreadPool(int idleTimeout, int maxWorkerThreads, int minWorkerThreads)
  306. {
  307. m_stpStartInfo = new STPStartInfo
  308. {
  309. IdleTimeout = idleTimeout,
  310. MaxWorkerThreads = maxWorkerThreads,
  311. MinWorkerThreads = minWorkerThreads,
  312. };
  313. Initialize();
  314. }
  315. /// <summary>
  316. /// Constructor
  317. /// </summary>
  318. /// <param name="stpStartInfo">A SmartThreadPool configuration that overrides the default behavior</param>
  319. public SmartThreadPool(STPStartInfo stpStartInfo)
  320. {
  321. m_stpStartInfo = new STPStartInfo(stpStartInfo);
  322. Initialize();
  323. }
  324. private void Initialize()
  325. {
  326. Name = m_stpStartInfo.ThreadPoolName;
  327. ValidateSTPStartInfo();
  328. // _stpStartInfoRW stores a read/write copy of the STPStartInfo.
  329. // Actually only MaxWorkerThreads and MinWorkerThreads are overwritten
  330. m_isSuspended = m_stpStartInfo.StartSuspended;
  331. // If the STP is not started suspended then start the threads.
  332. if (!m_isSuspended)
  333. {
  334. StartOptimalNumberOfThreads();
  335. }
  336. }
  337. private void StartOptimalNumberOfThreads()
  338. {
  339. int threadsCount;
  340. lock (m_workerThreadsLock)
  341. {
  342. threadsCount = m_workItemsQueue.Count;
  343. if (threadsCount == m_stpStartInfo.MinWorkerThreads)
  344. return;
  345. if (threadsCount < m_stpStartInfo.MinWorkerThreads)
  346. threadsCount = m_stpStartInfo.MinWorkerThreads;
  347. else if (threadsCount > m_stpStartInfo.MaxWorkerThreads)
  348. threadsCount = m_stpStartInfo.MaxWorkerThreads;
  349. threadsCount -= m_workerThreads.Count;
  350. }
  351. StartThreads(threadsCount);
  352. }
  353. private void ValidateSTPStartInfo()
  354. {
  355. if (m_stpStartInfo.MinWorkerThreads < 0)
  356. {
  357. throw new ArgumentOutOfRangeException(
  358. "MinWorkerThreads", "MinWorkerThreads cannot be negative");
  359. }
  360. if (m_stpStartInfo.MaxWorkerThreads <= 0)
  361. {
  362. throw new ArgumentOutOfRangeException(
  363. "MaxWorkerThreads", "MaxWorkerThreads must be greater than zero");
  364. }
  365. if (m_stpStartInfo.MinWorkerThreads > m_stpStartInfo.MaxWorkerThreads)
  366. {
  367. throw new ArgumentOutOfRangeException(
  368. "MinWorkerThreads, maxWorkerThreads",
  369. "MaxWorkerThreads must be greater or equal to MinWorkerThreads");
  370. }
  371. }
  372. #endregion
  373. #region Thread Processing
  374. /// <summary>
  375. /// Waits on the queue for a work item, shutdown, or timeout.
  376. /// </summary>
  377. /// <returns>
  378. /// Returns the WaitingCallback or null in case of timeout or shutdown.
  379. /// </returns>
  380. private WorkItem Dequeue()
  381. {
  382. return m_workItemsQueue.DequeueWorkItem(m_stpStartInfo.IdleTimeout, m_shuttingDownEvent);
  383. }
  384. /// <summary>
  385. /// Put a new work item in the queue
  386. /// </summary>
  387. /// <param name="workItem">A work item to queue</param>
  388. internal override void Enqueue(WorkItem workItem)
  389. {
  390. // Make sure the workItem is not null
  391. Debug.Assert(workItem is not null);
  392. IncrementWorkItemsCount();
  393. workItem.CanceledSmartThreadPool = m_canceledSmartThreadPool;
  394. workItem.WorkItemIsQueued();
  395. m_workItemsQueue.EnqueueWorkItem(workItem);
  396. // If all the threads are busy then try to create a new one
  397. if (m_currentWorkItemsCount > m_workerThreads.Count)
  398. {
  399. StartThreads(1);
  400. }
  401. }
  402. private void IncrementWorkItemsCount()
  403. {
  404. int count = Interlocked.Increment(ref m_currentWorkItemsCount);
  405. //Trace.WriteLine("WorkItemsCount = " + _currentWorkItemsCount.ToString());
  406. if (count == 1)
  407. {
  408. IsIdle = false;
  409. m_isIdleWaitHandle.Reset();
  410. }
  411. }
  412. private void DecrementWorkItemsCount()
  413. {
  414. int count = Interlocked.Decrement(ref m_currentWorkItemsCount);
  415. //Trace.WriteLine("WorkItemsCount = " + _currentWorkItemsCount.ToString());
  416. if (count == 0)
  417. {
  418. IsIdle = true;
  419. m_isIdleWaitHandle.Set();
  420. }
  421. Interlocked.Increment(ref m_workItemsProcessed);
  422. }
  423. private int baseWorkIDs = Environment.TickCount;
  424. internal void RegisterWorkItemsGroup(IWorkItemsGroup workItemsGroup)
  425. {
  426. int localID = Interlocked.Increment(ref baseWorkIDs);
  427. while (m_workItemsGroups.ContainsKey(localID))
  428. localID = Interlocked.Increment(ref baseWorkIDs);
  429. workItemsGroup.localID = localID;
  430. m_workItemsGroups[localID] = (WorkItemsGroup)workItemsGroup;
  431. }
  432. internal void UnregisterWorkItemsGroup(IWorkItemsGroup workItemsGroup)
  433. {
  434. m_workItemsGroups.TryRemove(workItemsGroup.localID, out WorkItemsGroup _);
  435. }
  436. /// <summary>
  437. /// Inform that the current thread is about to quit or quiting.
  438. /// The same thread may call this method more than once.
  439. /// </summary>
  440. private void InformCompleted()
  441. {
  442. if (m_workerThreads.TryRemove(Environment.CurrentManagedThreadId, out ThreadEntry te))
  443. {
  444. te.Clean();
  445. }
  446. }
  447. /// <summary>
  448. /// Starts new threads
  449. /// </summary>
  450. /// <param name="threadsCount">The number of threads to start</param>
  451. private void StartThreads(int threadsCount)
  452. {
  453. if (m_isSuspended)
  454. return;
  455. lock (m_workerThreadsLock)
  456. {
  457. // Don't start threads on shut down
  458. if (m_shutdown)
  459. return;
  460. int tmpcount = m_workerThreads.Count;
  461. if(tmpcount > m_stpStartInfo.MinWorkerThreads)
  462. {
  463. long last = Interlocked.Read(ref m_lastThreadCreateTS);
  464. if (DateTime.UtcNow.Ticks - last < 50 * TimeSpan.TicksPerMillisecond)
  465. return;
  466. }
  467. tmpcount = m_stpStartInfo.MaxWorkerThreads - tmpcount;
  468. if (threadsCount > tmpcount)
  469. threadsCount = tmpcount;
  470. while(threadsCount > 0)
  471. {
  472. // Create a new thread
  473. Thread workerThread;
  474. if(m_stpStartInfo.SuppressFlow)
  475. {
  476. using(ExecutionContext.SuppressFlow())
  477. {
  478. workerThread =
  479. m_stpStartInfo.MaxStackSize.HasValue
  480. ? new Thread(ProcessQueuedItems, m_stpStartInfo.MaxStackSize.Value)
  481. : new Thread(ProcessQueuedItems);
  482. }
  483. }
  484. else
  485. {
  486. workerThread =
  487. m_stpStartInfo.MaxStackSize.HasValue
  488. ? new Thread(ProcessQueuedItems, m_stpStartInfo.MaxStackSize.Value)
  489. : new Thread(ProcessQueuedItems);
  490. }
  491. // Configure the new thread and start it
  492. workerThread.IsBackground = m_stpStartInfo.AreThreadsBackground;
  493. if (m_stpStartInfo.ApartmentState != ApartmentState.Unknown)
  494. workerThread.SetApartmentState(m_stpStartInfo.ApartmentState);
  495. workerThread.Priority = m_stpStartInfo.ThreadPriority;
  496. workerThread.Name = $"STP:{Name}:{m_threadCounter}";
  497. Interlocked.Exchange(ref m_lastThreadCreateTS, DateTime.UtcNow.Ticks);
  498. ++m_threadCounter;
  499. --threadsCount;
  500. // Add it to the dictionary and update its creation time.
  501. m_workerThreads[workerThread.ManagedThreadId] = new ThreadEntry(this, workerThread);
  502. workerThread.Start();
  503. }
  504. }
  505. }
  506. /// <summary>
  507. /// A worker thread method that processes work items from the work items queue.
  508. /// </summary>
  509. private void ProcessQueuedItems()
  510. {
  511. // Keep the entry of the dictionary as thread's variable to avoid the synchronization locks
  512. // of the dictionary.
  513. CurrentThreadEntry = m_workerThreads[Environment.CurrentManagedThreadId];
  514. bool informedCompleted = false;
  515. FireOnThreadInitialization();
  516. try
  517. {
  518. bool bInUseWorkerThreadsWasIncremented = false;
  519. int maxworkers = m_stpStartInfo.MaxWorkerThreads;
  520. int minworkers = m_stpStartInfo.MinWorkerThreads;
  521. // Process until shutdown.
  522. while (!m_shutdown)
  523. {
  524. // The following block handles the when the MaxWorkerThreads has been
  525. // incremented by the user at run-time.
  526. // Double lock for quit.
  527. if (m_workerThreads.Count > maxworkers)
  528. {
  529. lock (m_workerThreadsLock)
  530. {
  531. if (m_workerThreads.Count > maxworkers)
  532. {
  533. // Inform that the thread is quiting and then quit.
  534. // This method must be called within this lock or else
  535. // more threads will quit and the thread pool will go
  536. // below the lower limit.
  537. InformCompleted();
  538. informedCompleted = true;
  539. break;
  540. }
  541. }
  542. }
  543. CurrentThreadEntry.IAmAlive();
  544. // Wait for a work item, shutdown, or timeout
  545. WorkItem workItem = Dequeue();
  546. // On timeout or shut down.
  547. if (workItem is null)
  548. {
  549. // Double lock for quit.
  550. if (m_workerThreads.Count > minworkers)
  551. {
  552. lock (m_workerThreadsLock)
  553. {
  554. if (m_workerThreads.Count > minworkers)
  555. {
  556. // Inform that the thread is quiting and then quit.
  557. // This method must be called within this lock or else
  558. // more threads will quit and the thread pool will go
  559. // below the lower limit.
  560. InformCompleted();
  561. informedCompleted = true;
  562. break;
  563. }
  564. }
  565. }
  566. continue;
  567. }
  568. CurrentThreadEntry.IAmAlive();
  569. try
  570. {
  571. // Initialize the value to false
  572. bInUseWorkerThreadsWasIncremented = false;
  573. // Set the Current Work Item of the thread.
  574. // Store the Current Work Item before the workItem.StartingWorkItem() is called,
  575. // so WorkItem.Cancel can work when the work item is between InQueue and InProgress
  576. // states.
  577. // If the work item has been cancelled BEFORE the workItem.StartingWorkItem()
  578. // (work item is in InQueue state) then workItem.StartingWorkItem() will return false.
  579. // If the work item has been cancelled AFTER the workItem.StartingWorkItem() then
  580. // (work item is in InProgress state) then the thread will be aborted
  581. CurrentThreadEntry.CurrentWorkItem = workItem;
  582. // Change the state of the work item to 'in progress' if possible.
  583. // We do it here so if the work item has been canceled we won't
  584. // increment the _inUseWorkerThreads.
  585. // The cancel mechanism doesn't delete items from the queue,
  586. // it marks the work item as canceled, and when the work item
  587. // is dequeued, we just skip it.
  588. // If the post execute of work item is set to always or to
  589. // call when the work item is canceled then the StartingWorkItem()
  590. // will return true, so the post execute can run.
  591. if (!workItem.StartingWorkItem())
  592. {
  593. CurrentThreadEntry.CurrentWorkItem = null;
  594. continue;
  595. }
  596. // Execute the callback. Make sure to accurately
  597. // record how many callbacks are currently executing.
  598. int inUseWorkerThreads = Interlocked.Increment(ref m_inUseWorkerThreads);
  599. // Mark that the _inUseWorkerThreads incremented, so in the finally{}
  600. // statement we will decrement it correctly.
  601. bInUseWorkerThreadsWasIncremented = true;
  602. workItem.FireWorkItemStarted();
  603. ExecuteWorkItem(workItem);
  604. }
  605. catch (Exception ex)
  606. {
  607. ex.GetHashCode();
  608. // Do nothing
  609. }
  610. finally
  611. {
  612. workItem.DisposeOfState();
  613. // Set the CurrentWorkItem to null, since we
  614. // no longer run user's code.
  615. CurrentThreadEntry.CurrentWorkItem = null;
  616. // Decrement the _inUseWorkerThreads only if we had
  617. // incremented it. Note the cancelled work items don't
  618. // increment _inUseWorkerThreads.
  619. if (bInUseWorkerThreadsWasIncremented)
  620. {
  621. int inUseWorkerThreads = Interlocked.Decrement(ref m_inUseWorkerThreads);
  622. }
  623. // Notify that the work item has been completed.
  624. // WorkItemsGroup may enqueue their next work item.
  625. workItem.FireWorkItemCompleted();
  626. // Decrement the number of work items here so the idle
  627. // ManualResetEvent won't fluctuate.
  628. DecrementWorkItemsCount();
  629. }
  630. }
  631. }
  632. /*
  633. catch (ThreadAbortException tae)
  634. {
  635. //tae.GetHashCode();
  636. // Handle the abort exception gracfully.
  637. //Thread.ResetAbort();
  638. }
  639. */
  640. catch (Exception e)
  641. {
  642. Debug.Assert(e is not null);
  643. }
  644. finally
  645. {
  646. if(!informedCompleted)
  647. InformCompleted();
  648. FireOnThreadTermination();
  649. m_workItemsQueue.CloseThreadWaiter();
  650. CurrentThreadEntry = null;
  651. }
  652. }
  653. private static void ExecuteWorkItem(WorkItem workItem)
  654. {
  655. try
  656. {
  657. workItem.Execute();
  658. }
  659. finally
  660. {
  661. }
  662. }
  663. #endregion
  664. #region Public Methods
  665. private void ValidateWaitForIdle()
  666. {
  667. if (CurrentThreadEntry is not null && CurrentThreadEntry.AssociatedSmartThreadPool == this)
  668. {
  669. throw new NotSupportedException(
  670. "WaitForIdle cannot be called from a thread on its SmartThreadPool, it causes a deadlock");
  671. }
  672. }
  673. internal static void ValidateWorkItemsGroupWaitForIdle(IWorkItemsGroup workItemsGroup)
  674. {
  675. if (CurrentThreadEntry is not null)
  676. ValidateWorkItemsGroupWaitForIdleImpl(workItemsGroup, CurrentThreadEntry.CurrentWorkItem);
  677. }
  678. [MethodImpl(MethodImplOptions.NoInlining)]
  679. private static void ValidateWorkItemsGroupWaitForIdleImpl(IWorkItemsGroup workItemsGroup, WorkItem workItem)
  680. {
  681. if ((workItemsGroup is not null) &&
  682. (workItem is not null) &&
  683. workItem.WasQueuedBy(workItemsGroup))
  684. {
  685. throw new NotSupportedException("WaitForIdle cannot be called from a thread on its SmartThreadPool, it causes a deadlock");
  686. }
  687. }
  688. /// <summary>
  689. /// Force the SmartThreadPool to shutdown
  690. /// </summary>
  691. public void Shutdown()
  692. {
  693. Shutdown(0);
  694. }
  695. /// <summary>
  696. /// Force the SmartThreadPool to shutdown with timeout
  697. /// </summary>
  698. public void Shutdown(TimeSpan timeout)
  699. {
  700. Shutdown((int)timeout.TotalMilliseconds);
  701. }
  702. /// <summary>
  703. /// Empties the queue of work items and abort the threads in the pool.
  704. /// </summary>
  705. public void Shutdown(int millisecondsTimeout)
  706. {
  707. ValidateNotDisposed();
  708. ThreadEntry[] threadEntries;
  709. lock (m_workerThreadsLock)
  710. {
  711. // Shutdown the work items queue
  712. m_workItemsQueue.Dispose();
  713. // Signal the threads to exit
  714. m_shutdown = true;
  715. m_shuttingDownEvent.Set();
  716. // Make a copy of the threads' references in the pool
  717. threadEntries = new ThreadEntry[m_workerThreads.Count];
  718. m_workerThreads.Values.CopyTo(threadEntries, 0);
  719. m_workerThreads.Clear();
  720. }
  721. int millisecondsLeft = millisecondsTimeout;
  722. Stopwatch stopwatch = Stopwatch.StartNew();
  723. if (millisecondsLeft >= Timeout.Infinite)
  724. {
  725. foreach (ThreadEntry te in threadEntries)
  726. {
  727. if (te is null)
  728. continue;
  729. Thread thread = te.WorkThread;
  730. if(thread is null)
  731. continue;
  732. if (thread.IsAlive)
  733. {
  734. // Wait for the thread to terminate
  735. _ = thread.Join(millisecondsLeft);
  736. if (millisecondsLeft > 0)
  737. {
  738. // Update the time left to wait
  739. millisecondsLeft = millisecondsTimeout - (int)stopwatch.ElapsedMilliseconds;
  740. if (millisecondsLeft < 0)
  741. millisecondsLeft= 0;
  742. }
  743. }
  744. te.WorkThread = null;
  745. }
  746. }
  747. else
  748. {
  749. // there is no Abort in dotnet > 5, so we can't do anything
  750. foreach (ThreadEntry te in threadEntries)
  751. {
  752. if (te is null)
  753. continue;
  754. te.WorkThread = null;
  755. }
  756. }
  757. }
  758. /// <summary>
  759. /// Wait for all work items to complete
  760. /// </summary>
  761. /// <param name="waitableResults">Array of work item result objects</param>
  762. /// <returns>
  763. /// true when every work item in workItemResults has completed; otherwise false.
  764. /// </returns>
  765. public static bool WaitAll( IWaitableResult[] waitableResults)
  766. {
  767. return WaitAll(waitableResults, Timeout.Infinite, true);
  768. }
  769. /// <summary>
  770. /// Wait for all work items to complete
  771. /// </summary>
  772. /// <param name="waitableResults">Array of work item result objects</param>
  773. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  774. /// <param name="exitContext">
  775. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  776. /// </param>
  777. /// <returns>
  778. /// true when every work item in workItemResults has completed; otherwise false.
  779. /// </returns>
  780. public static bool WaitAll( IWaitableResult[] waitableResults, TimeSpan timeout, bool exitContext)
  781. {
  782. return WaitAll(waitableResults, (int)timeout.TotalMilliseconds, exitContext);
  783. }
  784. /// <summary>
  785. /// Wait for all work items to complete
  786. /// </summary>
  787. /// <param name="waitableResults">Array of work item result objects</param>
  788. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  789. /// <param name="exitContext">
  790. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  791. /// </param>
  792. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  793. /// <returns>
  794. /// true when every work item in workItemResults has completed; otherwise false.
  795. /// </returns>
  796. public static bool WaitAll( IWaitableResult[] waitableResults, TimeSpan timeout,
  797. bool exitContext, WaitHandle cancelWaitHandle)
  798. {
  799. return WaitAll(waitableResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  800. }
  801. /// <summary>
  802. /// Wait for all work items to complete
  803. /// </summary>
  804. /// <param name="waitableResults">Array of work item result objects</param>
  805. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  806. /// <param name="exitContext">
  807. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  808. /// </param>
  809. /// <returns>
  810. /// true when every work item in workItemResults has completed; otherwise false.
  811. /// </returns>
  812. public static bool WaitAll( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext)
  813. {
  814. return WorkItem.WaitAll(waitableResults, millisecondsTimeout, exitContext, null);
  815. }
  816. /// <summary>
  817. /// Wait for all work items to complete
  818. /// </summary>
  819. /// <param name="waitableResults">Array of work item result objects</param>
  820. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  821. /// <param name="exitContext">
  822. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  823. /// </param>
  824. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  825. /// <returns>
  826. /// true when every work item in workItemResults has completed; otherwise false.
  827. /// </returns>
  828. public static bool WaitAll( IWaitableResult[] waitableResults, int millisecondsTimeout,
  829. bool exitContext, WaitHandle cancelWaitHandle)
  830. {
  831. return WorkItem.WaitAll(waitableResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  832. }
  833. /// <summary>
  834. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  835. /// </summary>
  836. /// <param name="waitableResults">Array of work item result objects</param>
  837. /// <returns>
  838. /// The array index of the work item result that satisfied the wait, or WaitTimeout if any of the work items has been canceled.
  839. /// </returns>
  840. public static int WaitAny( IWaitableResult[] waitableResults)
  841. {
  842. return WaitAny(waitableResults, Timeout.Infinite, true);
  843. }
  844. /// <summary>
  845. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  846. /// </summary>
  847. /// <param name="waitableResults">Array of work item result objects</param>
  848. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  849. /// <param name="exitContext">
  850. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  851. /// </param>
  852. /// <returns>
  853. /// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
  854. /// </returns>
  855. public static int WaitAny( IWaitableResult[] waitableResults, TimeSpan timeout, bool exitContext)
  856. {
  857. return WaitAny(waitableResults, (int)timeout.TotalMilliseconds, exitContext);
  858. }
  859. /// <summary>
  860. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  861. /// </summary>
  862. /// <param name="waitableResults">Array of work item result objects</param>
  863. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  864. /// <param name="exitContext">
  865. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  866. /// </param>
  867. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  868. /// <returns>
  869. /// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
  870. /// </returns>
  871. public static int WaitAny( IWaitableResult[] waitableResults, TimeSpan timeout,
  872. bool exitContext, WaitHandle cancelWaitHandle)
  873. {
  874. return WaitAny(waitableResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  875. }
  876. /// <summary>
  877. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  878. /// </summary>
  879. /// <param name="waitableResults">Array of work item result objects</param>
  880. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  881. /// <param name="exitContext">
  882. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  883. /// </param>
  884. /// <returns>
  885. /// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
  886. /// </returns>
  887. public static int WaitAny( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext)
  888. {
  889. return WorkItem.WaitAny(waitableResults, millisecondsTimeout, exitContext, null);
  890. }
  891. /// <summary>
  892. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  893. /// </summary>
  894. /// <param name="waitableResults">Array of work item result objects</param>
  895. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  896. /// <param name="exitContext">
  897. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  898. /// </param>
  899. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  900. /// <returns>
  901. /// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled.
  902. /// </returns>
  903. public static int WaitAny( IWaitableResult[] waitableResults, int millisecondsTimeout,
  904. bool exitContext, WaitHandle cancelWaitHandle)
  905. {
  906. return WorkItem.WaitAny(waitableResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  907. }
  908. /// <summary>
  909. /// Creates a new WorkItemsGroup.
  910. /// </summary>
  911. /// <param name="concurrency">The number of work items that can be run concurrently</param>
  912. /// <returns>A reference to the WorkItemsGroup</returns>
  913. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency)
  914. {
  915. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, m_stpStartInfo);
  916. return workItemsGroup;
  917. }
  918. /// <summary>
  919. /// Creates a new WorkItemsGroup.
  920. /// </summary>
  921. /// <param name="concurrency">The number of work items that can be run concurrently</param>
  922. /// <param name="wigStartInfo">A WorkItemsGroup configuration that overrides the default behavior</param>
  923. /// <returns>A reference to the WorkItemsGroup</returns>
  924. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency, WIGStartInfo wigStartInfo)
  925. {
  926. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, wigStartInfo);
  927. return workItemsGroup;
  928. }
  929. #region Fire Thread's Events
  930. private void FireOnThreadInitialization()
  931. {
  932. if (null != m_onThreadInitialization)
  933. {
  934. foreach (ThreadInitializationHandler tih in m_onThreadInitialization.GetInvocationList())
  935. {
  936. try
  937. {
  938. tih();
  939. }
  940. catch
  941. {
  942. Debug.Assert(false);
  943. throw;
  944. }
  945. }
  946. }
  947. }
  948. private void FireOnThreadTermination()
  949. {
  950. if (null != m_onThreadTermination)
  951. {
  952. foreach (ThreadTerminationHandler tth in m_onThreadTermination.GetInvocationList())
  953. {
  954. try
  955. {
  956. tth();
  957. }
  958. catch
  959. {
  960. Debug.Assert(false);
  961. throw;
  962. }
  963. }
  964. }
  965. }
  966. #endregion
  967. /// <summary>
  968. /// This event is fired when a thread is created.
  969. /// Use it to initialize a thread before the work items use it.
  970. /// </summary>
  971. public event ThreadInitializationHandler OnThreadInitialization
  972. {
  973. add { m_onThreadInitialization += value; }
  974. remove { m_onThreadInitialization -= value; }
  975. }
  976. /// <summary>
  977. /// This event is fired when a thread is terminating.
  978. /// Use it for cleanup.
  979. /// </summary>
  980. public event ThreadTerminationHandler OnThreadTermination
  981. {
  982. add { m_onThreadTermination += value; }
  983. remove { m_onThreadTermination -= value; }
  984. }
  985. internal void CancelAbortWorkItemsGroup(WorkItemsGroup wig)
  986. {
  987. foreach (ThreadEntry threadEntry in m_workerThreads.Values)
  988. {
  989. WorkItem workItem = threadEntry.CurrentWorkItem;
  990. if (null != workItem && !workItem.IsCanceled && workItem.WasQueuedBy(wig))
  991. {
  992. threadEntry.CurrentWorkItem.GetWorkItemResult().Cancel(true);
  993. }
  994. }
  995. }
  996. #endregion
  997. #region Properties
  998. /// <summary>
  999. /// Get/Set the lower limit of threads in the pool.
  1000. /// </summary>
  1001. public int MinThreads
  1002. {
  1003. get
  1004. {
  1005. ValidateNotDisposed();
  1006. return m_stpStartInfo.MinWorkerThreads;
  1007. }
  1008. set
  1009. {
  1010. Debug.Assert(value >= 0);
  1011. Debug.Assert(value <= m_stpStartInfo.MaxWorkerThreads);
  1012. if (m_stpStartInfo.MaxWorkerThreads < value)
  1013. {
  1014. m_stpStartInfo.MaxWorkerThreads = value;
  1015. }
  1016. m_stpStartInfo.MinWorkerThreads = value;
  1017. StartOptimalNumberOfThreads();
  1018. }
  1019. }
  1020. /// <summary>
  1021. /// Get/Set the upper limit of threads in the pool.
  1022. /// </summary>
  1023. public int MaxThreads
  1024. {
  1025. get
  1026. {
  1027. ValidateNotDisposed();
  1028. return m_stpStartInfo.MaxWorkerThreads;
  1029. }
  1030. set
  1031. {
  1032. Debug.Assert(value > 0);
  1033. Debug.Assert(value >= m_stpStartInfo.MinWorkerThreads);
  1034. if (m_stpStartInfo.MinWorkerThreads > value)
  1035. {
  1036. m_stpStartInfo.MinWorkerThreads = value;
  1037. }
  1038. m_stpStartInfo.MaxWorkerThreads = value;
  1039. StartOptimalNumberOfThreads();
  1040. }
  1041. }
  1042. /// <summary>
  1043. /// Get the number of threads in the thread pool.
  1044. /// Should be between the lower and the upper limits.
  1045. /// </summary>
  1046. public int ActiveThreads
  1047. {
  1048. get
  1049. {
  1050. ValidateNotDisposed();
  1051. return m_workerThreads.Count;
  1052. }
  1053. }
  1054. /// <summary>
  1055. /// Get the number of busy (not idle) threads in the thread pool.
  1056. /// </summary>
  1057. public int InUseThreads
  1058. {
  1059. get
  1060. {
  1061. ValidateNotDisposed();
  1062. return m_inUseWorkerThreads;
  1063. }
  1064. }
  1065. /// <summary>
  1066. /// Returns true if the current running work item has been cancelled.
  1067. /// Must be used within the work item's callback method.
  1068. /// The work item should sample this value in order to know if it
  1069. /// needs to quit before its completion.
  1070. /// </summary>
  1071. public static bool IsWorkItemCanceled
  1072. {
  1073. get
  1074. {
  1075. return CurrentThreadEntry.CurrentWorkItem.IsCanceled;
  1076. }
  1077. }
  1078. /// <summary>
  1079. /// Checks if the work item has been cancelled, and if yes then abort the thread.
  1080. /// Can be used with Cancel and timeout
  1081. /// </summary>
  1082. public static void AbortOnWorkItemCancel()
  1083. {
  1084. if (IsWorkItemCanceled)
  1085. {
  1086. //Thread.CurrentThread.Abort();
  1087. }
  1088. }
  1089. /// <summary>
  1090. /// Thread Pool start information (readonly)
  1091. /// </summary>
  1092. public STPStartInfo STPStartInfo
  1093. {
  1094. get
  1095. {
  1096. return m_stpStartInfo.AsReadOnly();
  1097. }
  1098. }
  1099. public bool IsShuttingdown
  1100. {
  1101. get { return m_shutdown; }
  1102. }
  1103. #endregion
  1104. #region IDisposable Members
  1105. public void Dispose()
  1106. {
  1107. Dispose(true);
  1108. GC.SuppressFinalize(this);
  1109. }
  1110. protected void Dispose(bool disposing)
  1111. {
  1112. if (!m_isDisposed)
  1113. {
  1114. if (!m_shutdown)
  1115. {
  1116. Shutdown();
  1117. }
  1118. if (m_shuttingDownEvent is not null)
  1119. {
  1120. m_shuttingDownEvent.Close();
  1121. m_shuttingDownEvent = null;
  1122. }
  1123. m_workerThreads.Clear();
  1124. if (m_isIdleWaitHandle is not null)
  1125. {
  1126. m_isIdleWaitHandle.Close();
  1127. m_isIdleWaitHandle = null;
  1128. }
  1129. m_isDisposed = true;
  1130. }
  1131. }
  1132. private void ValidateNotDisposed()
  1133. {
  1134. if (m_isDisposed)
  1135. {
  1136. throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown");
  1137. }
  1138. }
  1139. #endregion
  1140. #region WorkItemsGroupBase Overrides
  1141. /// <summary>
  1142. /// Get/Set the maximum number of work items that execute cocurrency on the thread pool
  1143. /// </summary>
  1144. public override int Concurrency
  1145. {
  1146. get { return MaxThreads; }
  1147. set { MaxThreads = value; }
  1148. }
  1149. /// <summary>
  1150. /// Get the number of work items in the queue.
  1151. /// </summary>
  1152. public override int WaitingCallbacks
  1153. {
  1154. get
  1155. {
  1156. ValidateNotDisposed();
  1157. return m_workItemsQueue.Count;
  1158. }
  1159. }
  1160. /// <summary>
  1161. /// Get an array with all the state objects of the currently running items.
  1162. /// The array represents a snap shot and impact performance.
  1163. /// </summary>
  1164. public override object[] GetStates()
  1165. {
  1166. object[] states = m_workItemsQueue.GetStates();
  1167. return states;
  1168. }
  1169. /// <summary>
  1170. /// WorkItemsGroup start information (readonly)
  1171. /// </summary>
  1172. public override WIGStartInfo WIGStartInfo
  1173. {
  1174. get { return m_stpStartInfo.AsReadOnly(); }
  1175. }
  1176. /// <summary>
  1177. /// Start the thread pool if it was started suspended.
  1178. /// If it is already running, this method is ignored.
  1179. /// </summary>
  1180. public override void Start()
  1181. {
  1182. if (!m_isSuspended)
  1183. {
  1184. return;
  1185. }
  1186. m_isSuspended = false;
  1187. foreach (WorkItemsGroup workItemsGroup in m_workItemsGroups.Values)
  1188. {
  1189. workItemsGroup?.OnSTPIsStarting();
  1190. }
  1191. StartOptimalNumberOfThreads();
  1192. }
  1193. /// <summary>
  1194. /// Cancel all work items using thread abortion
  1195. /// </summary>
  1196. /// <param name="abortExecution">True to stop work items by raising ThreadAbortException</param>
  1197. public override void Cancel(bool abortExecution)
  1198. {
  1199. m_canceledSmartThreadPool.IsCanceled = true;
  1200. m_canceledSmartThreadPool = new CanceledWorkItemsGroup();
  1201. foreach (WorkItemsGroup workItemsGroup in m_workItemsGroups.Values)
  1202. {
  1203. workItemsGroup?.Cancel(abortExecution);
  1204. }
  1205. if (abortExecution)
  1206. {
  1207. foreach (ThreadEntry threadEntry in m_workerThreads.Values)
  1208. {
  1209. if(threadEntry.AssociatedSmartThreadPool == this)
  1210. {
  1211. WorkItem workItem = threadEntry.CurrentWorkItem;
  1212. if (workItem is not null && !workItem.IsCanceled)
  1213. {
  1214. threadEntry.CurrentWorkItem.GetWorkItemResult().Cancel(true);
  1215. }
  1216. }
  1217. }
  1218. }
  1219. }
  1220. /// <summary>
  1221. /// Wait for the thread pool to be idle
  1222. /// </summary>
  1223. public override bool WaitForIdle(int millisecondsTimeout)
  1224. {
  1225. ValidateWaitForIdle();
  1226. return STPEventWaitHandle.WaitOne(m_isIdleWaitHandle, millisecondsTimeout, false);
  1227. }
  1228. /// <summary>
  1229. /// This event is fired when all work items are completed.
  1230. /// (When IsIdle changes to true)
  1231. /// This event only work on WorkItemsGroup. On SmartThreadPool
  1232. /// it throws the NotImplementedException.
  1233. /// </summary>
  1234. public override event WorkItemsGroupIdleHandler OnIdle
  1235. {
  1236. add
  1237. {
  1238. //_onIdle += value;
  1239. }
  1240. remove
  1241. {
  1242. //_onIdle -= value;
  1243. }
  1244. }
  1245. internal override void PreQueueWorkItem()
  1246. {
  1247. ValidateNotDisposed();
  1248. }
  1249. #endregion
  1250. #region Join, Choice, Pipe, etc.
  1251. /// <summary>
  1252. /// Executes all actions in parallel.
  1253. /// Returns when they all finish.
  1254. /// </summary>
  1255. /// <param name="actions">Actions to execute</param>
  1256. public void Join(IEnumerable<Action> actions)
  1257. {
  1258. WIGStartInfo wigStartInfo = new() { StartSuspended = true };
  1259. IWorkItemsGroup workItemsGroup = CreateWorkItemsGroup(int.MaxValue, wigStartInfo);
  1260. foreach (Action action in actions)
  1261. {
  1262. workItemsGroup.QueueWorkItem(action);
  1263. }
  1264. workItemsGroup.Start();
  1265. workItemsGroup.WaitForIdle();
  1266. }
  1267. /// <summary>
  1268. /// Executes all actions in parallel.
  1269. /// Returns when they all finish.
  1270. /// </summary>
  1271. /// <param name="actions">Actions to execute</param>
  1272. public void Join(params Action[] actions)
  1273. {
  1274. Join((IEnumerable<Action>)actions);
  1275. }
  1276. private class ChoiceIndex
  1277. {
  1278. public int _index = -1;
  1279. }
  1280. /// <summary>
  1281. /// Executes all actions in parallel
  1282. /// Returns when the first one completes
  1283. /// </summary>
  1284. /// <param name="actions">Actions to execute</param>
  1285. public int Choice(IEnumerable<Action> actions)
  1286. {
  1287. WIGStartInfo wigStartInfo = new() { StartSuspended = true };
  1288. IWorkItemsGroup workItemsGroup = CreateWorkItemsGroup(int.MaxValue, wigStartInfo);
  1289. ManualResetEvent anActionCompleted = new(false);
  1290. ChoiceIndex choiceIndex = new();
  1291. int i = 0;
  1292. foreach (Action action in actions)
  1293. {
  1294. Action act = action;
  1295. int value = i;
  1296. workItemsGroup.QueueWorkItem(() => { act(); Interlocked.CompareExchange(ref choiceIndex._index, value, -1); anActionCompleted.Set(); });
  1297. ++i;
  1298. }
  1299. workItemsGroup.Start();
  1300. anActionCompleted.WaitOne();
  1301. anActionCompleted.Dispose();
  1302. return choiceIndex._index;
  1303. }
  1304. /// <summary>
  1305. /// Executes all actions in parallel
  1306. /// Returns when the first one completes
  1307. /// </summary>
  1308. /// <param name="actions">Actions to execute</param>
  1309. public int Choice(params Action[] actions)
  1310. {
  1311. return Choice((IEnumerable<Action>)actions);
  1312. }
  1313. /// <summary>
  1314. /// Executes actions in sequence asynchronously.
  1315. /// Returns immediately.
  1316. /// </summary>
  1317. /// <param name="pipeState">A state context that passes </param>
  1318. /// <param name="actions">Actions to execute in the order they should run</param>
  1319. public void Pipe<T>(T pipeState, IEnumerable<Action<T>> actions)
  1320. {
  1321. WIGStartInfo wigStartInfo = new() { StartSuspended = true };
  1322. IWorkItemsGroup workItemsGroup = CreateWorkItemsGroup(1, wigStartInfo);
  1323. foreach (Action<T> action in actions)
  1324. {
  1325. Action<T> act = action;
  1326. workItemsGroup.QueueWorkItem(() => act(pipeState));
  1327. }
  1328. workItemsGroup.Start();
  1329. workItemsGroup.WaitForIdle();
  1330. }
  1331. /// <summary>
  1332. /// Executes actions in sequence asynchronously.
  1333. /// Returns immediately.
  1334. /// </summary>
  1335. /// <param name="pipeState"></param>
  1336. /// <param name="actions">Actions to execute in the order they should run</param>
  1337. public void Pipe<T>(T pipeState, params Action<T>[] actions)
  1338. {
  1339. Pipe(pipeState, (IEnumerable<Action<T>>)actions);
  1340. }
  1341. #endregion
  1342. }
  1343. #endregion
  1344. }