SmartThreadPool.cs 62 KB

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