SmartThreadPool.cs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  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;
  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 SynchronizedDictionary<Thread, ThreadEntry> _workerThreads = new SynchronizedDictionary<Thread, ThreadEntry>();
  183. /// <summary>
  184. /// Queue of work items.
  185. /// </summary>
  186. private readonly WorkItemsQueue _workItemsQueue = new WorkItemsQueue();
  187. /// <summary>
  188. /// Count the work items handled.
  189. /// Used by the performance counter.
  190. /// </summary>
  191. private int _workItemsProcessed;
  192. /// <summary>
  193. /// Number of threads that currently work (not idle).
  194. /// </summary>
  195. private int _inUseWorkerThreads;
  196. /// <summary>
  197. /// Stores a copy of the original STPStartInfo.
  198. /// It is used to change the MinThread and MaxThreads
  199. /// </summary>
  200. private STPStartInfo _stpStartInfo;
  201. /// <summary>
  202. /// Total number of work items that are stored in the work items queue
  203. /// plus the work items that the threads in the pool are working on.
  204. /// </summary>
  205. private int _currentWorkItemsCount;
  206. /// <summary>
  207. /// Signaled when the thread pool is idle, i.e. no thread is busy
  208. /// and the work items queue is empty
  209. /// </summary>
  210. private ManualResetEvent _isIdleWaitHandle = new ManualResetEvent(true);
  211. /// <summary>
  212. /// An event to signal all the threads to quit immediately.
  213. /// </summary>
  214. private ManualResetEvent _shuttingDownEvent = new ManualResetEvent(false);
  215. /// <summary>
  216. /// A flag to indicate if the Smart Thread Pool is now suspended.
  217. /// </summary>
  218. private bool _isSuspended;
  219. /// <summary>
  220. /// A flag to indicate the threads to quit.
  221. /// </summary>
  222. private bool _shutdown;
  223. /// <summary>
  224. /// Counts the threads created in the pool.
  225. /// It is used to name the threads.
  226. /// </summary>
  227. private int _threadCounter;
  228. /// <summary>
  229. /// Indicate that the SmartThreadPool has been disposed
  230. /// </summary>
  231. private bool _isDisposed;
  232. private static long _lastThreadCreateTS = long.MinValue;
  233. /// <summary>
  234. /// Holds all the WorkItemsGroup instaces that have at least one
  235. /// work item int the SmartThreadPool
  236. /// This variable is used in case of Shutdown
  237. /// </summary>
  238. private readonly SynchronizedDictionary<IWorkItemsGroup, IWorkItemsGroup> _workItemsGroups = new SynchronizedDictionary<IWorkItemsGroup, IWorkItemsGroup>();
  239. /// <summary>
  240. /// A common object for all the work items int the STP
  241. /// so we can mark them to cancel in O(1)
  242. /// </summary>
  243. private CanceledWorkItemsGroup _canceledSmartThreadPool = new CanceledWorkItemsGroup();
  244. /// <summary>
  245. /// Windows STP performance counters
  246. /// </summary>
  247. private ISTPInstancePerformanceCounters _windowsPCs = NullSTPInstancePerformanceCounters.Instance;
  248. /// <summary>
  249. /// Local STP performance counters
  250. /// </summary>
  251. private ISTPInstancePerformanceCounters _localPCs = NullSTPInstancePerformanceCounters.Instance;
  252. [ThreadStatic]
  253. private static ThreadEntry _threadEntry;
  254. /// <summary>
  255. /// An event to call after a thread is created, but before
  256. /// it's first use.
  257. /// </summary>
  258. private event ThreadInitializationHandler _onThreadInitialization;
  259. /// <summary>
  260. /// An event to call when a thread is about to exit, after
  261. /// it is no longer belong to the pool.
  262. /// </summary>
  263. private event ThreadTerminationHandler _onThreadTermination;
  264. #endregion
  265. #region Per thread properties
  266. /// <summary>
  267. /// A reference to the current work item a thread from the thread pool
  268. /// is executing.
  269. /// </summary>
  270. internal static ThreadEntry CurrentThreadEntry
  271. {
  272. get
  273. {
  274. return _threadEntry;
  275. }
  276. set
  277. {
  278. _threadEntry = value;
  279. }
  280. }
  281. #endregion
  282. #region Construction and Finalization
  283. /// <summary>
  284. /// Constructor
  285. /// </summary>
  286. public SmartThreadPool()
  287. {
  288. _stpStartInfo = new STPStartInfo();
  289. Initialize();
  290. }
  291. /// <summary>
  292. /// Constructor
  293. /// </summary>
  294. /// <param name="idleTimeout">Idle timeout in milliseconds</param>
  295. public SmartThreadPool(int idleTimeout)
  296. {
  297. _stpStartInfo = new STPStartInfo
  298. {
  299. IdleTimeout = idleTimeout,
  300. };
  301. Initialize();
  302. }
  303. /// <summary>
  304. /// Constructor
  305. /// </summary>
  306. /// <param name="idleTimeout">Idle timeout in milliseconds</param>
  307. /// <param name="maxWorkerThreads">Upper limit of threads in the pool</param>
  308. public SmartThreadPool(
  309. int idleTimeout,
  310. int maxWorkerThreads)
  311. {
  312. _stpStartInfo = new STPStartInfo
  313. {
  314. IdleTimeout = idleTimeout,
  315. MaxWorkerThreads = maxWorkerThreads,
  316. };
  317. Initialize();
  318. }
  319. /// <summary>
  320. /// Constructor
  321. /// </summary>
  322. /// <param name="idleTimeout">Idle timeout in milliseconds</param>
  323. /// <param name="maxWorkerThreads">Upper limit of threads in the pool</param>
  324. /// <param name="minWorkerThreads">Lower limit of threads in the pool</param>
  325. public SmartThreadPool(
  326. int idleTimeout,
  327. int maxWorkerThreads,
  328. int minWorkerThreads)
  329. {
  330. _stpStartInfo = new STPStartInfo
  331. {
  332. IdleTimeout = idleTimeout,
  333. MaxWorkerThreads = maxWorkerThreads,
  334. MinWorkerThreads = minWorkerThreads,
  335. };
  336. Initialize();
  337. }
  338. /// <summary>
  339. /// Constructor
  340. /// </summary>
  341. /// <param name="stpStartInfo">A SmartThreadPool configuration that overrides the default behavior</param>
  342. public SmartThreadPool(STPStartInfo stpStartInfo)
  343. {
  344. _stpStartInfo = new STPStartInfo(stpStartInfo);
  345. Initialize();
  346. }
  347. private void Initialize()
  348. {
  349. Name = _stpStartInfo.ThreadPoolName;
  350. ValidateSTPStartInfo();
  351. // _stpStartInfoRW stores a read/write copy of the STPStartInfo.
  352. // Actually only MaxWorkerThreads and MinWorkerThreads are overwritten
  353. _isSuspended = _stpStartInfo.StartSuspended;
  354. if (null != _stpStartInfo.PerformanceCounterInstanceName)
  355. {
  356. try
  357. {
  358. _windowsPCs = new STPInstancePerformanceCounters(_stpStartInfo.PerformanceCounterInstanceName);
  359. }
  360. catch (Exception e)
  361. {
  362. Debug.WriteLine("Unable to create Performance Counters: " + e);
  363. _windowsPCs = NullSTPInstancePerformanceCounters.Instance;
  364. }
  365. }
  366. if (_stpStartInfo.EnableLocalPerformanceCounters)
  367. {
  368. _localPCs = new LocalSTPInstancePerformanceCounters();
  369. }
  370. // If the STP is not started suspended then start the threads.
  371. if (!_isSuspended)
  372. {
  373. StartOptimalNumberOfThreads();
  374. }
  375. }
  376. private void StartOptimalNumberOfThreads()
  377. {
  378. int threadsCount;
  379. lock (_workerThreads.SyncRoot)
  380. {
  381. threadsCount = _workItemsQueue.Count;
  382. if (threadsCount == _stpStartInfo.MinWorkerThreads)
  383. return;
  384. if (threadsCount < _stpStartInfo.MinWorkerThreads)
  385. threadsCount = _stpStartInfo.MinWorkerThreads;
  386. else if (threadsCount > _stpStartInfo.MaxWorkerThreads)
  387. threadsCount = _stpStartInfo.MaxWorkerThreads;
  388. threadsCount -= _workerThreads.Count;
  389. }
  390. StartThreads(threadsCount);
  391. }
  392. private void ValidateSTPStartInfo()
  393. {
  394. if (_stpStartInfo.MinWorkerThreads < 0)
  395. {
  396. throw new ArgumentOutOfRangeException(
  397. "MinWorkerThreads", "MinWorkerThreads cannot be negative");
  398. }
  399. if (_stpStartInfo.MaxWorkerThreads <= 0)
  400. {
  401. throw new ArgumentOutOfRangeException(
  402. "MaxWorkerThreads", "MaxWorkerThreads must be greater than zero");
  403. }
  404. if (_stpStartInfo.MinWorkerThreads > _stpStartInfo.MaxWorkerThreads)
  405. {
  406. throw new ArgumentOutOfRangeException(
  407. "MinWorkerThreads, maxWorkerThreads",
  408. "MaxWorkerThreads must be greater or equal to MinWorkerThreads");
  409. }
  410. }
  411. private static void ValidateCallback(Delegate callback)
  412. {
  413. if (callback.GetInvocationList().Length > 1)
  414. {
  415. throw new NotSupportedException("SmartThreadPool doesn't support delegates chains");
  416. }
  417. }
  418. #endregion
  419. #region Thread Processing
  420. /// <summary>
  421. /// Waits on the queue for a work item, shutdown, or timeout.
  422. /// </summary>
  423. /// <returns>
  424. /// Returns the WaitingCallback or null in case of timeout or shutdown.
  425. /// </returns>
  426. private WorkItem Dequeue()
  427. {
  428. WorkItem workItem =
  429. _workItemsQueue.DequeueWorkItem(_stpStartInfo.IdleTimeout, _shuttingDownEvent);
  430. return workItem;
  431. }
  432. /// <summary>
  433. /// Put a new work item in the queue
  434. /// </summary>
  435. /// <param name="workItem">A work item to queue</param>
  436. internal override void Enqueue(WorkItem workItem)
  437. {
  438. // Make sure the workItem is not null
  439. Debug.Assert(null != workItem);
  440. IncrementWorkItemsCount();
  441. workItem.CanceledSmartThreadPool = _canceledSmartThreadPool;
  442. _workItemsQueue.EnqueueWorkItem(workItem);
  443. workItem.WorkItemIsQueued();
  444. // If all the threads are busy then try to create a new one
  445. if (_currentWorkItemsCount > _workerThreads.Count)
  446. {
  447. StartThreads(1);
  448. }
  449. }
  450. private void IncrementWorkItemsCount()
  451. {
  452. _windowsPCs.SampleWorkItems(_workItemsQueue.Count, _workItemsProcessed);
  453. _localPCs.SampleWorkItems(_workItemsQueue.Count, _workItemsProcessed);
  454. int count = Interlocked.Increment(ref _currentWorkItemsCount);
  455. //Trace.WriteLine("WorkItemsCount = " + _currentWorkItemsCount.ToString());
  456. if (count == 1)
  457. {
  458. IsIdle = false;
  459. _isIdleWaitHandle.Reset();
  460. }
  461. }
  462. private void DecrementWorkItemsCount()
  463. {
  464. int count = Interlocked.Decrement(ref _currentWorkItemsCount);
  465. //Trace.WriteLine("WorkItemsCount = " + _currentWorkItemsCount.ToString());
  466. if (count == 0)
  467. {
  468. IsIdle = true;
  469. _isIdleWaitHandle.Set();
  470. }
  471. Interlocked.Increment(ref _workItemsProcessed);
  472. if (!_shutdown)
  473. {
  474. // The counter counts even if the work item was cancelled
  475. _windowsPCs.SampleWorkItems(_workItemsQueue.Count, _workItemsProcessed);
  476. _localPCs.SampleWorkItems(_workItemsQueue.Count, _workItemsProcessed);
  477. }
  478. }
  479. internal void RegisterWorkItemsGroup(IWorkItemsGroup workItemsGroup)
  480. {
  481. _workItemsGroups[workItemsGroup] = workItemsGroup;
  482. }
  483. internal void UnregisterWorkItemsGroup(IWorkItemsGroup workItemsGroup)
  484. {
  485. if (_workItemsGroups.Contains(workItemsGroup))
  486. {
  487. _workItemsGroups.Remove(workItemsGroup);
  488. }
  489. }
  490. /// <summary>
  491. /// Inform that the current thread is about to quit or quiting.
  492. /// The same thread may call this method more than once.
  493. /// </summary>
  494. private void InformCompleted()
  495. {
  496. // There is no need to lock the two methods together
  497. // since only the current thread removes itself
  498. // and the _workerThreads is a synchronized dictionary
  499. if (_workerThreads.Contains(Thread.CurrentThread))
  500. {
  501. _workerThreads.Remove(Thread.CurrentThread);
  502. _windowsPCs.SampleThreads(_workerThreads.Count, _inUseWorkerThreads);
  503. _localPCs.SampleThreads(_workerThreads.Count, _inUseWorkerThreads);
  504. }
  505. }
  506. /// <summary>
  507. /// Starts new threads
  508. /// </summary>
  509. /// <param name="threadsCount">The number of threads to start</param>
  510. private void StartThreads(int threadsCount)
  511. {
  512. if (_isSuspended)
  513. return;
  514. lock (_workerThreads.SyncRoot)
  515. {
  516. // Don't start threads on shut down
  517. if (_shutdown)
  518. return;
  519. int tmpcount = _workerThreads.Count;
  520. if(tmpcount > _stpStartInfo.MinWorkerThreads)
  521. {
  522. long last = Interlocked.Read(ref _lastThreadCreateTS);
  523. if (DateTime.UtcNow.Ticks - last < 50 * TimeSpan.TicksPerMillisecond)
  524. return;
  525. }
  526. tmpcount = _stpStartInfo.MaxWorkerThreads - tmpcount;
  527. if (threadsCount > tmpcount)
  528. threadsCount = tmpcount;
  529. while(threadsCount > 0)
  530. {
  531. // Create a new thread
  532. Thread workerThread;
  533. if(_stpStartInfo.SuppressFlow)
  534. {
  535. using(ExecutionContext.SuppressFlow())
  536. {
  537. workerThread =
  538. _stpStartInfo.MaxStackSize.HasValue
  539. ? new Thread(ProcessQueuedItems, _stpStartInfo.MaxStackSize.Value)
  540. : new Thread(ProcessQueuedItems);
  541. }
  542. }
  543. else
  544. {
  545. workerThread =
  546. _stpStartInfo.MaxStackSize.HasValue
  547. ? new Thread(ProcessQueuedItems, _stpStartInfo.MaxStackSize.Value)
  548. : new Thread(ProcessQueuedItems);
  549. }
  550. // Configure the new thread and start it
  551. workerThread.IsBackground = _stpStartInfo.AreThreadsBackground;
  552. if (_stpStartInfo.ApartmentState != ApartmentState.Unknown)
  553. workerThread.SetApartmentState(_stpStartInfo.ApartmentState);
  554. workerThread.Priority = _stpStartInfo.ThreadPriority;
  555. workerThread.Name = string.Format("STP:{0}:{1}", Name, _threadCounter);
  556. workerThread.Start();
  557. Interlocked.Exchange(ref _lastThreadCreateTS, DateTime.UtcNow.Ticks);
  558. ++_threadCounter;
  559. --threadsCount;
  560. // Add it to the dictionary and update its creation time.
  561. _workerThreads[workerThread] = new ThreadEntry(this);
  562. _windowsPCs.SampleThreads(_workerThreads.Count, _inUseWorkerThreads);
  563. _localPCs.SampleThreads(_workerThreads.Count, _inUseWorkerThreads);
  564. }
  565. }
  566. }
  567. /// <summary>
  568. /// A worker thread method that processes work items from the work items queue.
  569. /// </summary>
  570. private void ProcessQueuedItems()
  571. {
  572. // Keep the entry of the dictionary as thread's variable to avoid the synchronization locks
  573. // of the dictionary.
  574. CurrentThreadEntry = _workerThreads[Thread.CurrentThread];
  575. bool informedCompleted = false;
  576. FireOnThreadInitialization();
  577. try
  578. {
  579. bool bInUseWorkerThreadsWasIncremented = false;
  580. int maxworkers = _stpStartInfo.MaxWorkerThreads;
  581. int minworkers = _stpStartInfo.MinWorkerThreads;
  582. // Process until shutdown.
  583. while (!_shutdown)
  584. {
  585. // The following block handles the when the MaxWorkerThreads has been
  586. // incremented by the user at run-time.
  587. // Double lock for quit.
  588. if (_workerThreads.Count > maxworkers)
  589. {
  590. lock (_workerThreads.SyncRoot)
  591. {
  592. if (_workerThreads.Count > maxworkers)
  593. {
  594. // Inform that the thread is quiting and then quit.
  595. // This method must be called within this lock or else
  596. // more threads will quit and the thread pool will go
  597. // below the lower limit.
  598. InformCompleted();
  599. informedCompleted = true;
  600. break;
  601. }
  602. }
  603. }
  604. CurrentThreadEntry.IAmAlive();
  605. // Wait for a work item, shutdown, or timeout
  606. WorkItem workItem = Dequeue();
  607. // On timeout or shut down.
  608. if (workItem == null)
  609. {
  610. // Double lock for quit.
  611. if (_workerThreads.Count > minworkers)
  612. {
  613. lock (_workerThreads.SyncRoot)
  614. {
  615. if (_workerThreads.Count > minworkers)
  616. {
  617. // Inform that the thread is quiting and then quit.
  618. // This method must be called within this lock or else
  619. // more threads will quit and the thread pool will go
  620. // below the lower limit.
  621. InformCompleted();
  622. informedCompleted = true;
  623. break;
  624. }
  625. }
  626. }
  627. continue;
  628. }
  629. CurrentThreadEntry.IAmAlive();
  630. try
  631. {
  632. // Initialize the value to false
  633. bInUseWorkerThreadsWasIncremented = false;
  634. // Set the Current Work Item of the thread.
  635. // Store the Current Work Item before the workItem.StartingWorkItem() is called,
  636. // so WorkItem.Cancel can work when the work item is between InQueue and InProgress
  637. // states.
  638. // If the work item has been cancelled BEFORE the workItem.StartingWorkItem()
  639. // (work item is in InQueue state) then workItem.StartingWorkItem() will return false.
  640. // If the work item has been cancelled AFTER the workItem.StartingWorkItem() then
  641. // (work item is in InProgress state) then the thread will be aborted
  642. CurrentThreadEntry.CurrentWorkItem = workItem;
  643. // Change the state of the work item to 'in progress' if possible.
  644. // We do it here so if the work item has been canceled we won't
  645. // increment the _inUseWorkerThreads.
  646. // The cancel mechanism doesn't delete items from the queue,
  647. // it marks the work item as canceled, and when the work item
  648. // is dequeued, we just skip it.
  649. // If the post execute of work item is set to always or to
  650. // call when the work item is canceled then the StartingWorkItem()
  651. // will return true, so the post execute can run.
  652. if (!workItem.StartingWorkItem())
  653. {
  654. CurrentThreadEntry.CurrentWorkItem = null;
  655. continue;
  656. }
  657. // Execute the callback. Make sure to accurately
  658. // record how many callbacks are currently executing.
  659. int inUseWorkerThreads = Interlocked.Increment(ref _inUseWorkerThreads);
  660. _windowsPCs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  661. _localPCs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  662. // Mark that the _inUseWorkerThreads incremented, so in the finally{}
  663. // statement we will decrement it correctly.
  664. bInUseWorkerThreadsWasIncremented = true;
  665. workItem.FireWorkItemStarted();
  666. ExecuteWorkItem(workItem);
  667. }
  668. catch (Exception ex)
  669. {
  670. ex.GetHashCode();
  671. // Do nothing
  672. }
  673. finally
  674. {
  675. workItem.DisposeOfState();
  676. // Set the CurrentWorkItem to null, since we
  677. // no longer run user's code.
  678. CurrentThreadEntry.CurrentWorkItem = null;
  679. // Decrement the _inUseWorkerThreads only if we had
  680. // incremented it. Note the cancelled work items don't
  681. // increment _inUseWorkerThreads.
  682. if (bInUseWorkerThreadsWasIncremented)
  683. {
  684. int inUseWorkerThreads = Interlocked.Decrement(ref _inUseWorkerThreads);
  685. _windowsPCs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  686. _localPCs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  687. }
  688. // Notify that the work item has been completed.
  689. // WorkItemsGroup may enqueue their next work item.
  690. workItem.FireWorkItemCompleted();
  691. // Decrement the number of work items here so the idle
  692. // ManualResetEvent won't fluctuate.
  693. DecrementWorkItemsCount();
  694. }
  695. }
  696. }
  697. catch (ThreadAbortException tae)
  698. {
  699. tae.GetHashCode();
  700. // Handle the abort exception gracfully.
  701. Thread.ResetAbort();
  702. }
  703. catch (Exception e)
  704. {
  705. Debug.Assert(null != e);
  706. }
  707. finally
  708. {
  709. if(!informedCompleted)
  710. InformCompleted();
  711. FireOnThreadTermination();
  712. _workItemsQueue.CloseThreadWaiter();
  713. }
  714. }
  715. private void ExecuteWorkItem(WorkItem workItem)
  716. {
  717. _windowsPCs.SampleWorkItemsWaitTime(workItem.WaitingTime);
  718. _localPCs.SampleWorkItemsWaitTime(workItem.WaitingTime);
  719. try
  720. {
  721. workItem.Execute();
  722. }
  723. finally
  724. {
  725. _windowsPCs.SampleWorkItemsProcessTime(workItem.ProcessTime);
  726. _localPCs.SampleWorkItemsProcessTime(workItem.ProcessTime);
  727. }
  728. }
  729. #endregion
  730. #region Public Methods
  731. private void ValidateWaitForIdle()
  732. {
  733. if (null != CurrentThreadEntry && CurrentThreadEntry.AssociatedSmartThreadPool == this)
  734. {
  735. throw new NotSupportedException(
  736. "WaitForIdle cannot be called from a thread on its SmartThreadPool, it causes a deadlock");
  737. }
  738. }
  739. internal static void ValidateWorkItemsGroupWaitForIdle(IWorkItemsGroup workItemsGroup)
  740. {
  741. if (null == CurrentThreadEntry)
  742. {
  743. return;
  744. }
  745. WorkItem workItem = CurrentThreadEntry.CurrentWorkItem;
  746. ValidateWorkItemsGroupWaitForIdleImpl(workItemsGroup, workItem);
  747. if ((null != workItemsGroup) &&
  748. (null != workItem) &&
  749. CurrentThreadEntry.CurrentWorkItem.WasQueuedBy(workItemsGroup))
  750. {
  751. throw new NotSupportedException("WaitForIdle cannot be called from a thread on its SmartThreadPool, it causes a deadlock");
  752. }
  753. }
  754. [MethodImpl(MethodImplOptions.NoInlining)]
  755. private static void ValidateWorkItemsGroupWaitForIdleImpl(IWorkItemsGroup workItemsGroup, WorkItem workItem)
  756. {
  757. if ((null != workItemsGroup) &&
  758. (null != workItem) &&
  759. workItem.WasQueuedBy(workItemsGroup))
  760. {
  761. throw new NotSupportedException("WaitForIdle cannot be called from a thread on its SmartThreadPool, it causes a deadlock");
  762. }
  763. }
  764. /// <summary>
  765. /// Force the SmartThreadPool to shutdown
  766. /// </summary>
  767. public void Shutdown()
  768. {
  769. Shutdown(true, 0);
  770. }
  771. /// <summary>
  772. /// Force the SmartThreadPool to shutdown with timeout
  773. /// </summary>
  774. public void Shutdown(bool forceAbort, TimeSpan timeout)
  775. {
  776. Shutdown(forceAbort, (int)timeout.TotalMilliseconds);
  777. }
  778. /// <summary>
  779. /// Empties the queue of work items and abort the threads in the pool.
  780. /// </summary>
  781. public void Shutdown(bool forceAbort, int millisecondsTimeout)
  782. {
  783. ValidateNotDisposed();
  784. ISTPInstancePerformanceCounters pcs = _windowsPCs;
  785. if (NullSTPInstancePerformanceCounters.Instance != _windowsPCs)
  786. {
  787. // Set the _pcs to "null" to stop updating the performance
  788. // counters
  789. _windowsPCs = NullSTPInstancePerformanceCounters.Instance;
  790. pcs.Dispose();
  791. }
  792. Thread[] threads;
  793. lock (_workerThreads.SyncRoot)
  794. {
  795. // Shutdown the work items queue
  796. _workItemsQueue.Dispose();
  797. // Signal the threads to exit
  798. _shutdown = true;
  799. _shuttingDownEvent.Set();
  800. // Make a copy of the threads' references in the pool
  801. threads = new Thread[_workerThreads.Count];
  802. _workerThreads.Keys.CopyTo(threads, 0);
  803. }
  804. int millisecondsLeft = millisecondsTimeout;
  805. Stopwatch stopwatch = Stopwatch.StartNew();
  806. //DateTime start = DateTime.UtcNow;
  807. bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
  808. bool timeout = false;
  809. // Each iteration we update the time left for the timeout.
  810. foreach (Thread thread in threads)
  811. {
  812. // Join don't work with negative numbers
  813. if (!waitInfinitely && (millisecondsLeft < 0))
  814. {
  815. timeout = true;
  816. break;
  817. }
  818. // Wait for the thread to terminate
  819. bool success = thread.Join(millisecondsLeft);
  820. if (!success)
  821. {
  822. timeout = true;
  823. break;
  824. }
  825. if (!waitInfinitely)
  826. {
  827. // Update the time left to wait
  828. //TimeSpan ts = DateTime.UtcNow - start;
  829. millisecondsLeft = millisecondsTimeout - (int)stopwatch.ElapsedMilliseconds;
  830. }
  831. }
  832. if (timeout && forceAbort)
  833. {
  834. // Abort the threads in the pool
  835. foreach (Thread thread in threads)
  836. {
  837. if ((thread != null) && thread.IsAlive )
  838. {
  839. try
  840. {
  841. thread.Abort(); // Shutdown
  842. }
  843. catch (SecurityException e)
  844. {
  845. e.GetHashCode();
  846. }
  847. catch (ThreadStateException ex)
  848. {
  849. ex.GetHashCode();
  850. // In case the thread has been terminated
  851. // after the check if it is alive.
  852. }
  853. }
  854. }
  855. }
  856. }
  857. /// <summary>
  858. /// Wait for all work items to complete
  859. /// </summary>
  860. /// <param name="waitableResults">Array of work item result objects</param>
  861. /// <returns>
  862. /// true when every work item in workItemResults has completed; otherwise false.
  863. /// </returns>
  864. public static bool WaitAll( IWaitableResult[] waitableResults)
  865. {
  866. return WaitAll(waitableResults, Timeout.Infinite, true);
  867. }
  868. /// <summary>
  869. /// Wait for all work items to complete
  870. /// </summary>
  871. /// <param name="waitableResults">Array of work item result objects</param>
  872. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  873. /// <param name="exitContext">
  874. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  875. /// </param>
  876. /// <returns>
  877. /// true when every work item in workItemResults has completed; otherwise false.
  878. /// </returns>
  879. public static bool WaitAll( IWaitableResult[] waitableResults, TimeSpan timeout, bool exitContext)
  880. {
  881. return WaitAll(waitableResults, (int)timeout.TotalMilliseconds, exitContext);
  882. }
  883. /// <summary>
  884. /// Wait for all work items to complete
  885. /// </summary>
  886. /// <param name="waitableResults">Array of work item result objects</param>
  887. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  888. /// <param name="exitContext">
  889. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  890. /// </param>
  891. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  892. /// <returns>
  893. /// true when every work item in workItemResults has completed; otherwise false.
  894. /// </returns>
  895. public static bool WaitAll( IWaitableResult[] waitableResults, TimeSpan timeout,
  896. bool exitContext, WaitHandle cancelWaitHandle)
  897. {
  898. return WaitAll(waitableResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  899. }
  900. /// <summary>
  901. /// Wait for all work items to complete
  902. /// </summary>
  903. /// <param name="waitableResults">Array of work item result objects</param>
  904. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  905. /// <param name="exitContext">
  906. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  907. /// </param>
  908. /// <returns>
  909. /// true when every work item in workItemResults has completed; otherwise false.
  910. /// </returns>
  911. public static bool WaitAll( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext)
  912. {
  913. return WorkItem.WaitAll(waitableResults, millisecondsTimeout, exitContext, null);
  914. }
  915. /// <summary>
  916. /// Wait for all work items to complete
  917. /// </summary>
  918. /// <param name="waitableResults">Array of work item result objects</param>
  919. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  920. /// <param name="exitContext">
  921. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  922. /// </param>
  923. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  924. /// <returns>
  925. /// true when every work item in workItemResults has completed; otherwise false.
  926. /// </returns>
  927. public static bool WaitAll( IWaitableResult[] waitableResults, int millisecondsTimeout,
  928. bool exitContext, WaitHandle cancelWaitHandle)
  929. {
  930. return WorkItem.WaitAll(waitableResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  931. }
  932. /// <summary>
  933. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  934. /// </summary>
  935. /// <param name="waitableResults">Array of work item result objects</param>
  936. /// <returns>
  937. /// The array index of the work item result that satisfied the wait, or WaitTimeout if any of the work items has been canceled.
  938. /// </returns>
  939. public static int WaitAny( IWaitableResult[] waitableResults)
  940. {
  941. return WaitAny(waitableResults, Timeout.Infinite, true);
  942. }
  943. /// <summary>
  944. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  945. /// </summary>
  946. /// <param name="waitableResults">Array of work item result objects</param>
  947. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  948. /// <param name="exitContext">
  949. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  950. /// </param>
  951. /// <returns>
  952. /// 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.
  953. /// </returns>
  954. public static int WaitAny( IWaitableResult[] waitableResults, TimeSpan timeout, bool exitContext)
  955. {
  956. return WaitAny(waitableResults, (int)timeout.TotalMilliseconds, exitContext);
  957. }
  958. /// <summary>
  959. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  960. /// </summary>
  961. /// <param name="waitableResults">Array of work item result objects</param>
  962. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  963. /// <param name="exitContext">
  964. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  965. /// </param>
  966. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  967. /// <returns>
  968. /// 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.
  969. /// </returns>
  970. public static int WaitAny( IWaitableResult[] waitableResults, TimeSpan timeout,
  971. bool exitContext, WaitHandle cancelWaitHandle)
  972. {
  973. return WaitAny(waitableResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  974. }
  975. /// <summary>
  976. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  977. /// </summary>
  978. /// <param name="waitableResults">Array of work item result objects</param>
  979. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  980. /// <param name="exitContext">
  981. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  982. /// </param>
  983. /// <returns>
  984. /// 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.
  985. /// </returns>
  986. public static int WaitAny( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext)
  987. {
  988. return WorkItem.WaitAny(waitableResults, millisecondsTimeout, exitContext, null);
  989. }
  990. /// <summary>
  991. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  992. /// </summary>
  993. /// <param name="waitableResults">Array of work item result objects</param>
  994. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  995. /// <param name="exitContext">
  996. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  997. /// </param>
  998. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  999. /// <returns>
  1000. /// 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.
  1001. /// </returns>
  1002. public static int WaitAny( IWaitableResult[] waitableResults, int millisecondsTimeout,
  1003. bool exitContext, WaitHandle cancelWaitHandle)
  1004. {
  1005. return WorkItem.WaitAny(waitableResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  1006. }
  1007. /// <summary>
  1008. /// Creates a new WorkItemsGroup.
  1009. /// </summary>
  1010. /// <param name="concurrency">The number of work items that can be run concurrently</param>
  1011. /// <returns>A reference to the WorkItemsGroup</returns>
  1012. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency)
  1013. {
  1014. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, _stpStartInfo);
  1015. return workItemsGroup;
  1016. }
  1017. /// <summary>
  1018. /// Creates a new WorkItemsGroup.
  1019. /// </summary>
  1020. /// <param name="concurrency">The number of work items that can be run concurrently</param>
  1021. /// <param name="wigStartInfo">A WorkItemsGroup configuration that overrides the default behavior</param>
  1022. /// <returns>A reference to the WorkItemsGroup</returns>
  1023. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency, WIGStartInfo wigStartInfo)
  1024. {
  1025. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, wigStartInfo);
  1026. return workItemsGroup;
  1027. }
  1028. #region Fire Thread's Events
  1029. private void FireOnThreadInitialization()
  1030. {
  1031. if (null != _onThreadInitialization)
  1032. {
  1033. foreach (ThreadInitializationHandler tih in _onThreadInitialization.GetInvocationList())
  1034. {
  1035. try
  1036. {
  1037. tih();
  1038. }
  1039. catch (Exception e)
  1040. {
  1041. e.GetHashCode();
  1042. Debug.Assert(false);
  1043. throw;
  1044. }
  1045. }
  1046. }
  1047. }
  1048. private void FireOnThreadTermination()
  1049. {
  1050. if (null != _onThreadTermination)
  1051. {
  1052. foreach (ThreadTerminationHandler tth in _onThreadTermination.GetInvocationList())
  1053. {
  1054. try
  1055. {
  1056. tth();
  1057. }
  1058. catch (Exception e)
  1059. {
  1060. e.GetHashCode();
  1061. Debug.Assert(false);
  1062. throw;
  1063. }
  1064. }
  1065. }
  1066. }
  1067. #endregion
  1068. /// <summary>
  1069. /// This event is fired when a thread is created.
  1070. /// Use it to initialize a thread before the work items use it.
  1071. /// </summary>
  1072. public event ThreadInitializationHandler OnThreadInitialization
  1073. {
  1074. add { _onThreadInitialization += value; }
  1075. remove { _onThreadInitialization -= value; }
  1076. }
  1077. /// <summary>
  1078. /// This event is fired when a thread is terminating.
  1079. /// Use it for cleanup.
  1080. /// </summary>
  1081. public event ThreadTerminationHandler OnThreadTermination
  1082. {
  1083. add { _onThreadTermination += value; }
  1084. remove { _onThreadTermination -= value; }
  1085. }
  1086. internal void CancelAbortWorkItemsGroup(WorkItemsGroup wig)
  1087. {
  1088. foreach (ThreadEntry threadEntry in _workerThreads.Values)
  1089. {
  1090. WorkItem workItem = threadEntry.CurrentWorkItem;
  1091. if (null != workItem &&
  1092. workItem.WasQueuedBy(wig) &&
  1093. !workItem.IsCanceled)
  1094. {
  1095. threadEntry.CurrentWorkItem.GetWorkItemResult().Cancel(true);
  1096. }
  1097. }
  1098. }
  1099. #endregion
  1100. #region Properties
  1101. /// <summary>
  1102. /// Get/Set the lower limit of threads in the pool.
  1103. /// </summary>
  1104. public int MinThreads
  1105. {
  1106. get
  1107. {
  1108. ValidateNotDisposed();
  1109. return _stpStartInfo.MinWorkerThreads;
  1110. }
  1111. set
  1112. {
  1113. Debug.Assert(value >= 0);
  1114. Debug.Assert(value <= _stpStartInfo.MaxWorkerThreads);
  1115. if (_stpStartInfo.MaxWorkerThreads < value)
  1116. {
  1117. _stpStartInfo.MaxWorkerThreads = value;
  1118. }
  1119. _stpStartInfo.MinWorkerThreads = value;
  1120. StartOptimalNumberOfThreads();
  1121. }
  1122. }
  1123. /// <summary>
  1124. /// Get/Set the upper limit of threads in the pool.
  1125. /// </summary>
  1126. public int MaxThreads
  1127. {
  1128. get
  1129. {
  1130. ValidateNotDisposed();
  1131. return _stpStartInfo.MaxWorkerThreads;
  1132. }
  1133. set
  1134. {
  1135. Debug.Assert(value > 0);
  1136. Debug.Assert(value >= _stpStartInfo.MinWorkerThreads);
  1137. if (_stpStartInfo.MinWorkerThreads > value)
  1138. {
  1139. _stpStartInfo.MinWorkerThreads = value;
  1140. }
  1141. _stpStartInfo.MaxWorkerThreads = value;
  1142. StartOptimalNumberOfThreads();
  1143. }
  1144. }
  1145. /// <summary>
  1146. /// Get the number of threads in the thread pool.
  1147. /// Should be between the lower and the upper limits.
  1148. /// </summary>
  1149. public int ActiveThreads
  1150. {
  1151. get
  1152. {
  1153. ValidateNotDisposed();
  1154. return _workerThreads.Count;
  1155. }
  1156. }
  1157. /// <summary>
  1158. /// Get the number of busy (not idle) threads in the thread pool.
  1159. /// </summary>
  1160. public int InUseThreads
  1161. {
  1162. get
  1163. {
  1164. ValidateNotDisposed();
  1165. return _inUseWorkerThreads;
  1166. }
  1167. }
  1168. /// <summary>
  1169. /// Returns true if the current running work item has been cancelled.
  1170. /// Must be used within the work item's callback method.
  1171. /// The work item should sample this value in order to know if it
  1172. /// needs to quit before its completion.
  1173. /// </summary>
  1174. public static bool IsWorkItemCanceled
  1175. {
  1176. get
  1177. {
  1178. return CurrentThreadEntry.CurrentWorkItem.IsCanceled;
  1179. }
  1180. }
  1181. /// <summary>
  1182. /// Checks if the work item has been cancelled, and if yes then abort the thread.
  1183. /// Can be used with Cancel and timeout
  1184. /// </summary>
  1185. public static void AbortOnWorkItemCancel()
  1186. {
  1187. if (IsWorkItemCanceled)
  1188. {
  1189. Thread.CurrentThread.Abort();
  1190. }
  1191. }
  1192. /// <summary>
  1193. /// Thread Pool start information (readonly)
  1194. /// </summary>
  1195. public STPStartInfo STPStartInfo
  1196. {
  1197. get
  1198. {
  1199. return _stpStartInfo.AsReadOnly();
  1200. }
  1201. }
  1202. public bool IsShuttingdown
  1203. {
  1204. get { return _shutdown; }
  1205. }
  1206. /// <summary>
  1207. /// Return the local calculated performance counters
  1208. /// Available only if STPStartInfo.EnableLocalPerformanceCounters is true.
  1209. /// </summary>
  1210. public ISTPPerformanceCountersReader PerformanceCountersReader
  1211. {
  1212. get { return (ISTPPerformanceCountersReader)_localPCs; }
  1213. }
  1214. #endregion
  1215. #region IDisposable Members
  1216. public void Dispose()
  1217. {
  1218. Dispose(true);
  1219. GC.SuppressFinalize(this);
  1220. }
  1221. protected void Dispose(bool disposing)
  1222. {
  1223. if (!_isDisposed)
  1224. {
  1225. if (!_shutdown)
  1226. {
  1227. Shutdown();
  1228. }
  1229. if (null != _shuttingDownEvent)
  1230. {
  1231. _shuttingDownEvent.Close();
  1232. _shuttingDownEvent = null;
  1233. }
  1234. _workerThreads.Clear();
  1235. if (null != _isIdleWaitHandle)
  1236. {
  1237. _isIdleWaitHandle.Close();
  1238. _isIdleWaitHandle = null;
  1239. }
  1240. if (_stpStartInfo.EnableLocalPerformanceCounters)
  1241. _localPCs.Dispose();
  1242. _isDisposed = true;
  1243. }
  1244. }
  1245. private void ValidateNotDisposed()
  1246. {
  1247. if (_isDisposed)
  1248. {
  1249. throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown");
  1250. }
  1251. }
  1252. #endregion
  1253. #region WorkItemsGroupBase Overrides
  1254. /// <summary>
  1255. /// Get/Set the maximum number of work items that execute cocurrency on the thread pool
  1256. /// </summary>
  1257. public override int Concurrency
  1258. {
  1259. get { return MaxThreads; }
  1260. set { MaxThreads = value; }
  1261. }
  1262. /// <summary>
  1263. /// Get the number of work items in the queue.
  1264. /// </summary>
  1265. public override int WaitingCallbacks
  1266. {
  1267. get
  1268. {
  1269. ValidateNotDisposed();
  1270. return _workItemsQueue.Count;
  1271. }
  1272. }
  1273. /// <summary>
  1274. /// Get an array with all the state objects of the currently running items.
  1275. /// The array represents a snap shot and impact performance.
  1276. /// </summary>
  1277. public override object[] GetStates()
  1278. {
  1279. object[] states = _workItemsQueue.GetStates();
  1280. return states;
  1281. }
  1282. /// <summary>
  1283. /// WorkItemsGroup start information (readonly)
  1284. /// </summary>
  1285. public override WIGStartInfo WIGStartInfo
  1286. {
  1287. get { return _stpStartInfo.AsReadOnly(); }
  1288. }
  1289. /// <summary>
  1290. /// Start the thread pool if it was started suspended.
  1291. /// If it is already running, this method is ignored.
  1292. /// </summary>
  1293. public override void Start()
  1294. {
  1295. if (!_isSuspended)
  1296. {
  1297. return;
  1298. }
  1299. _isSuspended = false;
  1300. ICollection workItemsGroups = _workItemsGroups.Values;
  1301. foreach (WorkItemsGroup workItemsGroup in workItemsGroups)
  1302. {
  1303. workItemsGroup.OnSTPIsStarting();
  1304. }
  1305. StartOptimalNumberOfThreads();
  1306. }
  1307. /// <summary>
  1308. /// Cancel all work items using thread abortion
  1309. /// </summary>
  1310. /// <param name="abortExecution">True to stop work items by raising ThreadAbortException</param>
  1311. public override void Cancel(bool abortExecution)
  1312. {
  1313. _canceledSmartThreadPool.IsCanceled = true;
  1314. _canceledSmartThreadPool = new CanceledWorkItemsGroup();
  1315. ICollection workItemsGroups = _workItemsGroups.Values;
  1316. foreach (WorkItemsGroup workItemsGroup in workItemsGroups)
  1317. {
  1318. workItemsGroup.Cancel(abortExecution);
  1319. }
  1320. if (abortExecution)
  1321. {
  1322. foreach (ThreadEntry threadEntry in _workerThreads.Values)
  1323. {
  1324. WorkItem workItem = threadEntry.CurrentWorkItem;
  1325. if (null != workItem &&
  1326. threadEntry.AssociatedSmartThreadPool == this &&
  1327. !workItem.IsCanceled)
  1328. {
  1329. threadEntry.CurrentWorkItem.GetWorkItemResult().Cancel(true);
  1330. }
  1331. }
  1332. }
  1333. }
  1334. /// <summary>
  1335. /// Wait for the thread pool to be idle
  1336. /// </summary>
  1337. public override bool WaitForIdle(int millisecondsTimeout)
  1338. {
  1339. ValidateWaitForIdle();
  1340. return STPEventWaitHandle.WaitOne(_isIdleWaitHandle, millisecondsTimeout, false);
  1341. }
  1342. /// <summary>
  1343. /// This event is fired when all work items are completed.
  1344. /// (When IsIdle changes to true)
  1345. /// This event only work on WorkItemsGroup. On SmartThreadPool
  1346. /// it throws the NotImplementedException.
  1347. /// </summary>
  1348. public override event WorkItemsGroupIdleHandler OnIdle
  1349. {
  1350. add
  1351. {
  1352. //_onIdle += value;
  1353. }
  1354. remove
  1355. {
  1356. //_onIdle -= value;
  1357. }
  1358. }
  1359. internal override void PreQueueWorkItem()
  1360. {
  1361. ValidateNotDisposed();
  1362. }
  1363. #endregion
  1364. #region Join, Choice, Pipe, etc.
  1365. /// <summary>
  1366. /// Executes all actions in parallel.
  1367. /// Returns when they all finish.
  1368. /// </summary>
  1369. /// <param name="actions">Actions to execute</param>
  1370. public void Join(IEnumerable<Action> actions)
  1371. {
  1372. WIGStartInfo wigStartInfo = new WIGStartInfo { StartSuspended = true };
  1373. IWorkItemsGroup workItemsGroup = CreateWorkItemsGroup(int.MaxValue, wigStartInfo);
  1374. foreach (Action action in actions)
  1375. {
  1376. workItemsGroup.QueueWorkItem(action);
  1377. }
  1378. workItemsGroup.Start();
  1379. workItemsGroup.WaitForIdle();
  1380. }
  1381. /// <summary>
  1382. /// Executes all actions in parallel.
  1383. /// Returns when they all finish.
  1384. /// </summary>
  1385. /// <param name="actions">Actions to execute</param>
  1386. public void Join(params Action[] actions)
  1387. {
  1388. Join((IEnumerable<Action>)actions);
  1389. }
  1390. private class ChoiceIndex
  1391. {
  1392. public int _index = -1;
  1393. }
  1394. /// <summary>
  1395. /// Executes all actions in parallel
  1396. /// Returns when the first one completes
  1397. /// </summary>
  1398. /// <param name="actions">Actions to execute</param>
  1399. public int Choice(IEnumerable<Action> actions)
  1400. {
  1401. WIGStartInfo wigStartInfo = new WIGStartInfo { StartSuspended = true };
  1402. IWorkItemsGroup workItemsGroup = CreateWorkItemsGroup(int.MaxValue, wigStartInfo);
  1403. ManualResetEvent anActionCompleted = new ManualResetEvent(false);
  1404. ChoiceIndex choiceIndex = new ChoiceIndex();
  1405. int i = 0;
  1406. foreach (Action action in actions)
  1407. {
  1408. Action act = action;
  1409. int value = i;
  1410. workItemsGroup.QueueWorkItem(() => { act(); Interlocked.CompareExchange(ref choiceIndex._index, value, -1); anActionCompleted.Set(); });
  1411. ++i;
  1412. }
  1413. workItemsGroup.Start();
  1414. anActionCompleted.WaitOne();
  1415. anActionCompleted.Dispose();
  1416. return choiceIndex._index;
  1417. }
  1418. /// <summary>
  1419. /// Executes all actions in parallel
  1420. /// Returns when the first one completes
  1421. /// </summary>
  1422. /// <param name="actions">Actions to execute</param>
  1423. public int Choice(params Action[] actions)
  1424. {
  1425. return Choice((IEnumerable<Action>)actions);
  1426. }
  1427. /// <summary>
  1428. /// Executes actions in sequence asynchronously.
  1429. /// Returns immediately.
  1430. /// </summary>
  1431. /// <param name="pipeState">A state context that passes </param>
  1432. /// <param name="actions">Actions to execute in the order they should run</param>
  1433. public void Pipe<T>(T pipeState, IEnumerable<Action<T>> actions)
  1434. {
  1435. WIGStartInfo wigStartInfo = new WIGStartInfo { StartSuspended = true };
  1436. IWorkItemsGroup workItemsGroup = CreateWorkItemsGroup(1, wigStartInfo);
  1437. foreach (Action<T> action in actions)
  1438. {
  1439. Action<T> act = action;
  1440. workItemsGroup.QueueWorkItem(() => act(pipeState));
  1441. }
  1442. workItemsGroup.Start();
  1443. workItemsGroup.WaitForIdle();
  1444. }
  1445. /// <summary>
  1446. /// Executes actions in sequence asynchronously.
  1447. /// Returns immediately.
  1448. /// </summary>
  1449. /// <param name="pipeState"></param>
  1450. /// <param name="actions">Actions to execute in the order they should run</param>
  1451. public void Pipe<T>(T pipeState, params Action<T>[] actions)
  1452. {
  1453. Pipe(pipeState, (IEnumerable<Action<T>>)actions);
  1454. }
  1455. #endregion
  1456. }
  1457. #endregion
  1458. }