SmartThreadPool.cs 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  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. FireOnThreadInitialization();
  576. try
  577. {
  578. bool bInUseWorkerThreadsWasIncremented = false;
  579. int maxworkers = _stpStartInfo.MaxWorkerThreads;
  580. int minworkers = _stpStartInfo.MinWorkerThreads;
  581. // Process until shutdown.
  582. while (!_shutdown)
  583. {
  584. // Update the last time this thread was seen alive.
  585. // It's good for debugging.
  586. CurrentThreadEntry.IAmAlive();
  587. // The following block handles the when the MaxWorkerThreads has been
  588. // incremented by the user at run-time.
  589. // Double lock for quit.
  590. if (_workerThreads.Count > maxworkers)
  591. {
  592. lock (_workerThreads.SyncRoot)
  593. {
  594. if (_workerThreads.Count > maxworkers)
  595. {
  596. // Inform that the thread is quiting and then quit.
  597. // This method must be called within this lock or else
  598. // more threads will quit and the thread pool will go
  599. // below the lower limit.
  600. InformCompleted();
  601. break;
  602. }
  603. }
  604. }
  605. // Wait for a work item, shutdown, or timeout
  606. WorkItem workItem = Dequeue();
  607. // Update the last time this thread was seen alive.
  608. // It's good for debugging.
  609. CurrentThreadEntry.IAmAlive();
  610. // On timeout or shut down.
  611. if (workItem == null)
  612. {
  613. // Double lock for quit.
  614. if (_workerThreads.Count > minworkers)
  615. {
  616. lock (_workerThreads.SyncRoot)
  617. {
  618. if (_workerThreads.Count > minworkers)
  619. {
  620. // Inform that the thread is quiting and then quit.
  621. // This method must be called within this lock or else
  622. // more threads will quit and the thread pool will go
  623. // below the lower limit.
  624. InformCompleted();
  625. break;
  626. }
  627. }
  628. }
  629. continue;
  630. }
  631. try
  632. {
  633. // Initialize the value to false
  634. bInUseWorkerThreadsWasIncremented = false;
  635. // Set the Current Work Item of the thread.
  636. // Store the Current Work Item before the workItem.StartingWorkItem() is called,
  637. // so WorkItem.Cancel can work when the work item is between InQueue and InProgress
  638. // states.
  639. // If the work item has been cancelled BEFORE the workItem.StartingWorkItem()
  640. // (work item is in InQueue state) then workItem.StartingWorkItem() will return false.
  641. // If the work item has been cancelled AFTER the workItem.StartingWorkItem() then
  642. // (work item is in InProgress state) then the thread will be aborted
  643. CurrentThreadEntry.CurrentWorkItem = workItem;
  644. // Change the state of the work item to 'in progress' if possible.
  645. // We do it here so if the work item has been canceled we won't
  646. // increment the _inUseWorkerThreads.
  647. // The cancel mechanism doesn't delete items from the queue,
  648. // it marks the work item as canceled, and when the work item
  649. // is dequeued, we just skip it.
  650. // If the post execute of work item is set to always or to
  651. // call when the work item is canceled then the StartingWorkItem()
  652. // will return true, so the post execute can run.
  653. if (!workItem.StartingWorkItem())
  654. {
  655. CurrentThreadEntry.CurrentWorkItem = null;
  656. continue;
  657. }
  658. // Execute the callback. Make sure to accurately
  659. // record how many callbacks are currently executing.
  660. int inUseWorkerThreads = Interlocked.Increment(ref _inUseWorkerThreads);
  661. _windowsPCs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  662. _localPCs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  663. // Mark that the _inUseWorkerThreads incremented, so in the finally{}
  664. // statement we will decrement it correctly.
  665. bInUseWorkerThreadsWasIncremented = true;
  666. workItem.FireWorkItemStarted();
  667. ExecuteWorkItem(workItem);
  668. }
  669. catch (Exception ex)
  670. {
  671. ex.GetHashCode();
  672. // Do nothing
  673. }
  674. finally
  675. {
  676. workItem.DisposeOfState();
  677. // Set the CurrentWorkItem to null, since we
  678. // no longer run user's code.
  679. CurrentThreadEntry.CurrentWorkItem = null;
  680. // Decrement the _inUseWorkerThreads only if we had
  681. // incremented it. Note the cancelled work items don't
  682. // increment _inUseWorkerThreads.
  683. if (bInUseWorkerThreadsWasIncremented)
  684. {
  685. int inUseWorkerThreads = Interlocked.Decrement(ref _inUseWorkerThreads);
  686. _windowsPCs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  687. _localPCs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  688. }
  689. // Notify that the work item has been completed.
  690. // WorkItemsGroup may enqueue their next work item.
  691. workItem.FireWorkItemCompleted();
  692. // Decrement the number of work items here so the idle
  693. // ManualResetEvent won't fluctuate.
  694. DecrementWorkItemsCount();
  695. }
  696. }
  697. }
  698. catch (ThreadAbortException tae)
  699. {
  700. tae.GetHashCode();
  701. // Handle the abort exception gracfully.
  702. Thread.ResetAbort();
  703. }
  704. catch (Exception e)
  705. {
  706. Debug.Assert(null != e);
  707. }
  708. finally
  709. {
  710. InformCompleted();
  711. FireOnThreadTermination();
  712. }
  713. }
  714. private void ExecuteWorkItem(WorkItem workItem)
  715. {
  716. _windowsPCs.SampleWorkItemsWaitTime(workItem.WaitingTime);
  717. _localPCs.SampleWorkItemsWaitTime(workItem.WaitingTime);
  718. try
  719. {
  720. workItem.Execute();
  721. }
  722. finally
  723. {
  724. _windowsPCs.SampleWorkItemsProcessTime(workItem.ProcessTime);
  725. _localPCs.SampleWorkItemsProcessTime(workItem.ProcessTime);
  726. }
  727. }
  728. #endregion
  729. #region Public Methods
  730. private void ValidateWaitForIdle()
  731. {
  732. if (null != CurrentThreadEntry && CurrentThreadEntry.AssociatedSmartThreadPool == this)
  733. {
  734. throw new NotSupportedException(
  735. "WaitForIdle cannot be called from a thread on its SmartThreadPool, it causes a deadlock");
  736. }
  737. }
  738. internal static void ValidateWorkItemsGroupWaitForIdle(IWorkItemsGroup workItemsGroup)
  739. {
  740. if (null == CurrentThreadEntry)
  741. {
  742. return;
  743. }
  744. WorkItem workItem = CurrentThreadEntry.CurrentWorkItem;
  745. ValidateWorkItemsGroupWaitForIdleImpl(workItemsGroup, workItem);
  746. if ((null != workItemsGroup) &&
  747. (null != workItem) &&
  748. CurrentThreadEntry.CurrentWorkItem.WasQueuedBy(workItemsGroup))
  749. {
  750. throw new NotSupportedException("WaitForIdle cannot be called from a thread on its SmartThreadPool, it causes a deadlock");
  751. }
  752. }
  753. [MethodImpl(MethodImplOptions.NoInlining)]
  754. private static void ValidateWorkItemsGroupWaitForIdleImpl(IWorkItemsGroup workItemsGroup, WorkItem workItem)
  755. {
  756. if ((null != workItemsGroup) &&
  757. (null != workItem) &&
  758. workItem.WasQueuedBy(workItemsGroup))
  759. {
  760. throw new NotSupportedException("WaitForIdle cannot be called from a thread on its SmartThreadPool, it causes a deadlock");
  761. }
  762. }
  763. /// <summary>
  764. /// Force the SmartThreadPool to shutdown
  765. /// </summary>
  766. public void Shutdown()
  767. {
  768. Shutdown(true, 0);
  769. }
  770. /// <summary>
  771. /// Force the SmartThreadPool to shutdown with timeout
  772. /// </summary>
  773. public void Shutdown(bool forceAbort, TimeSpan timeout)
  774. {
  775. Shutdown(forceAbort, (int)timeout.TotalMilliseconds);
  776. }
  777. /// <summary>
  778. /// Empties the queue of work items and abort the threads in the pool.
  779. /// </summary>
  780. public void Shutdown(bool forceAbort, int millisecondsTimeout)
  781. {
  782. ValidateNotDisposed();
  783. ISTPInstancePerformanceCounters pcs = _windowsPCs;
  784. if (NullSTPInstancePerformanceCounters.Instance != _windowsPCs)
  785. {
  786. // Set the _pcs to "null" to stop updating the performance
  787. // counters
  788. _windowsPCs = NullSTPInstancePerformanceCounters.Instance;
  789. pcs.Dispose();
  790. }
  791. Thread[] threads;
  792. lock (_workerThreads.SyncRoot)
  793. {
  794. // Shutdown the work items queue
  795. _workItemsQueue.Dispose();
  796. // Signal the threads to exit
  797. _shutdown = true;
  798. _shuttingDownEvent.Set();
  799. // Make a copy of the threads' references in the pool
  800. threads = new Thread[_workerThreads.Count];
  801. _workerThreads.Keys.CopyTo(threads, 0);
  802. }
  803. int millisecondsLeft = millisecondsTimeout;
  804. Stopwatch stopwatch = Stopwatch.StartNew();
  805. //DateTime start = DateTime.UtcNow;
  806. bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
  807. bool timeout = false;
  808. // Each iteration we update the time left for the timeout.
  809. foreach (Thread thread in threads)
  810. {
  811. // Join don't work with negative numbers
  812. if (!waitInfinitely && (millisecondsLeft < 0))
  813. {
  814. timeout = true;
  815. break;
  816. }
  817. // Wait for the thread to terminate
  818. bool success = thread.Join(millisecondsLeft);
  819. if (!success)
  820. {
  821. timeout = true;
  822. break;
  823. }
  824. if (!waitInfinitely)
  825. {
  826. // Update the time left to wait
  827. //TimeSpan ts = DateTime.UtcNow - start;
  828. millisecondsLeft = millisecondsTimeout - (int)stopwatch.ElapsedMilliseconds;
  829. }
  830. }
  831. if (timeout && forceAbort)
  832. {
  833. // Abort the threads in the pool
  834. foreach (Thread thread in threads)
  835. {
  836. if ((thread != null) && thread.IsAlive )
  837. {
  838. try
  839. {
  840. thread.Abort(); // Shutdown
  841. }
  842. catch (SecurityException e)
  843. {
  844. e.GetHashCode();
  845. }
  846. catch (ThreadStateException ex)
  847. {
  848. ex.GetHashCode();
  849. // In case the thread has been terminated
  850. // after the check if it is alive.
  851. }
  852. }
  853. }
  854. }
  855. }
  856. /// <summary>
  857. /// Wait for all work items to complete
  858. /// </summary>
  859. /// <param name="waitableResults">Array of work item result objects</param>
  860. /// <returns>
  861. /// true when every work item in workItemResults has completed; otherwise false.
  862. /// </returns>
  863. public static bool WaitAll( IWaitableResult[] waitableResults)
  864. {
  865. return WaitAll(waitableResults, Timeout.Infinite, true);
  866. }
  867. /// <summary>
  868. /// Wait for all work items to complete
  869. /// </summary>
  870. /// <param name="waitableResults">Array of work item result objects</param>
  871. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  872. /// <param name="exitContext">
  873. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  874. /// </param>
  875. /// <returns>
  876. /// true when every work item in workItemResults has completed; otherwise false.
  877. /// </returns>
  878. public static bool WaitAll( IWaitableResult[] waitableResults, TimeSpan timeout, bool exitContext)
  879. {
  880. return WaitAll(waitableResults, (int)timeout.TotalMilliseconds, exitContext);
  881. }
  882. /// <summary>
  883. /// Wait for all work items to complete
  884. /// </summary>
  885. /// <param name="waitableResults">Array of work item result objects</param>
  886. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  887. /// <param name="exitContext">
  888. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  889. /// </param>
  890. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  891. /// <returns>
  892. /// true when every work item in workItemResults has completed; otherwise false.
  893. /// </returns>
  894. public static bool WaitAll( IWaitableResult[] waitableResults, TimeSpan timeout,
  895. bool exitContext, WaitHandle cancelWaitHandle)
  896. {
  897. return WaitAll(waitableResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  898. }
  899. /// <summary>
  900. /// Wait for all work items to complete
  901. /// </summary>
  902. /// <param name="waitableResults">Array of work item result objects</param>
  903. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  904. /// <param name="exitContext">
  905. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  906. /// </param>
  907. /// <returns>
  908. /// true when every work item in workItemResults has completed; otherwise false.
  909. /// </returns>
  910. public static bool WaitAll( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext)
  911. {
  912. return WorkItem.WaitAll(waitableResults, millisecondsTimeout, exitContext, null);
  913. }
  914. /// <summary>
  915. /// Wait for all work items to complete
  916. /// </summary>
  917. /// <param name="waitableResults">Array of work item result objects</param>
  918. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  919. /// <param name="exitContext">
  920. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  921. /// </param>
  922. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  923. /// <returns>
  924. /// true when every work item in workItemResults has completed; otherwise false.
  925. /// </returns>
  926. public static bool WaitAll( IWaitableResult[] waitableResults, int millisecondsTimeout,
  927. bool exitContext, WaitHandle cancelWaitHandle)
  928. {
  929. return WorkItem.WaitAll(waitableResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  930. }
  931. /// <summary>
  932. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  933. /// </summary>
  934. /// <param name="waitableResults">Array of work item result objects</param>
  935. /// <returns>
  936. /// The array index of the work item result that satisfied the wait, or WaitTimeout if any of the work items has been canceled.
  937. /// </returns>
  938. public static int WaitAny( IWaitableResult[] waitableResults)
  939. {
  940. return WaitAny(waitableResults, Timeout.Infinite, true);
  941. }
  942. /// <summary>
  943. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  944. /// </summary>
  945. /// <param name="waitableResults">Array of work item result objects</param>
  946. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  947. /// <param name="exitContext">
  948. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  949. /// </param>
  950. /// <returns>
  951. /// 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.
  952. /// </returns>
  953. public static int WaitAny( IWaitableResult[] waitableResults, TimeSpan timeout, bool exitContext)
  954. {
  955. return WaitAny(waitableResults, (int)timeout.TotalMilliseconds, exitContext);
  956. }
  957. /// <summary>
  958. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  959. /// </summary>
  960. /// <param name="waitableResults">Array of work item result objects</param>
  961. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  962. /// <param name="exitContext">
  963. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  964. /// </param>
  965. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  966. /// <returns>
  967. /// 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.
  968. /// </returns>
  969. public static int WaitAny( IWaitableResult[] waitableResults, TimeSpan timeout,
  970. bool exitContext, WaitHandle cancelWaitHandle)
  971. {
  972. return WaitAny(waitableResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  973. }
  974. /// <summary>
  975. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  976. /// </summary>
  977. /// <param name="waitableResults">Array of work item result objects</param>
  978. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  979. /// <param name="exitContext">
  980. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  981. /// </param>
  982. /// <returns>
  983. /// 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.
  984. /// </returns>
  985. public static int WaitAny( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext)
  986. {
  987. return WorkItem.WaitAny(waitableResults, millisecondsTimeout, exitContext, null);
  988. }
  989. /// <summary>
  990. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  991. /// </summary>
  992. /// <param name="waitableResults">Array of work item result objects</param>
  993. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  994. /// <param name="exitContext">
  995. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  996. /// </param>
  997. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  998. /// <returns>
  999. /// 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.
  1000. /// </returns>
  1001. public static int WaitAny( IWaitableResult[] waitableResults, int millisecondsTimeout,
  1002. bool exitContext, WaitHandle cancelWaitHandle)
  1003. {
  1004. return WorkItem.WaitAny(waitableResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  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. /// <returns>A reference to the WorkItemsGroup</returns>
  1011. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency)
  1012. {
  1013. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, _stpStartInfo);
  1014. return workItemsGroup;
  1015. }
  1016. /// <summary>
  1017. /// Creates a new WorkItemsGroup.
  1018. /// </summary>
  1019. /// <param name="concurrency">The number of work items that can be run concurrently</param>
  1020. /// <param name="wigStartInfo">A WorkItemsGroup configuration that overrides the default behavior</param>
  1021. /// <returns>A reference to the WorkItemsGroup</returns>
  1022. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency, WIGStartInfo wigStartInfo)
  1023. {
  1024. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, wigStartInfo);
  1025. return workItemsGroup;
  1026. }
  1027. #region Fire Thread's Events
  1028. private void FireOnThreadInitialization()
  1029. {
  1030. if (null != _onThreadInitialization)
  1031. {
  1032. foreach (ThreadInitializationHandler tih in _onThreadInitialization.GetInvocationList())
  1033. {
  1034. try
  1035. {
  1036. tih();
  1037. }
  1038. catch (Exception e)
  1039. {
  1040. e.GetHashCode();
  1041. Debug.Assert(false);
  1042. throw;
  1043. }
  1044. }
  1045. }
  1046. }
  1047. private void FireOnThreadTermination()
  1048. {
  1049. if (null != _onThreadTermination)
  1050. {
  1051. foreach (ThreadTerminationHandler tth in _onThreadTermination.GetInvocationList())
  1052. {
  1053. try
  1054. {
  1055. tth();
  1056. }
  1057. catch (Exception e)
  1058. {
  1059. e.GetHashCode();
  1060. Debug.Assert(false);
  1061. throw;
  1062. }
  1063. }
  1064. }
  1065. }
  1066. #endregion
  1067. /// <summary>
  1068. /// This event is fired when a thread is created.
  1069. /// Use it to initialize a thread before the work items use it.
  1070. /// </summary>
  1071. public event ThreadInitializationHandler OnThreadInitialization
  1072. {
  1073. add { _onThreadInitialization += value; }
  1074. remove { _onThreadInitialization -= value; }
  1075. }
  1076. /// <summary>
  1077. /// This event is fired when a thread is terminating.
  1078. /// Use it for cleanup.
  1079. /// </summary>
  1080. public event ThreadTerminationHandler OnThreadTermination
  1081. {
  1082. add { _onThreadTermination += value; }
  1083. remove { _onThreadTermination -= value; }
  1084. }
  1085. internal void CancelAbortWorkItemsGroup(WorkItemsGroup wig)
  1086. {
  1087. foreach (ThreadEntry threadEntry in _workerThreads.Values)
  1088. {
  1089. WorkItem workItem = threadEntry.CurrentWorkItem;
  1090. if (null != workItem &&
  1091. workItem.WasQueuedBy(wig) &&
  1092. !workItem.IsCanceled)
  1093. {
  1094. threadEntry.CurrentWorkItem.GetWorkItemResult().Cancel(true);
  1095. }
  1096. }
  1097. }
  1098. #endregion
  1099. #region Properties
  1100. /// <summary>
  1101. /// Get/Set the lower limit of threads in the pool.
  1102. /// </summary>
  1103. public int MinThreads
  1104. {
  1105. get
  1106. {
  1107. ValidateNotDisposed();
  1108. return _stpStartInfo.MinWorkerThreads;
  1109. }
  1110. set
  1111. {
  1112. Debug.Assert(value >= 0);
  1113. Debug.Assert(value <= _stpStartInfo.MaxWorkerThreads);
  1114. if (_stpStartInfo.MaxWorkerThreads < value)
  1115. {
  1116. _stpStartInfo.MaxWorkerThreads = value;
  1117. }
  1118. _stpStartInfo.MinWorkerThreads = value;
  1119. StartOptimalNumberOfThreads();
  1120. }
  1121. }
  1122. /// <summary>
  1123. /// Get/Set the upper limit of threads in the pool.
  1124. /// </summary>
  1125. public int MaxThreads
  1126. {
  1127. get
  1128. {
  1129. ValidateNotDisposed();
  1130. return _stpStartInfo.MaxWorkerThreads;
  1131. }
  1132. set
  1133. {
  1134. Debug.Assert(value > 0);
  1135. Debug.Assert(value >= _stpStartInfo.MinWorkerThreads);
  1136. if (_stpStartInfo.MinWorkerThreads > value)
  1137. {
  1138. _stpStartInfo.MinWorkerThreads = value;
  1139. }
  1140. _stpStartInfo.MaxWorkerThreads = value;
  1141. StartOptimalNumberOfThreads();
  1142. }
  1143. }
  1144. /// <summary>
  1145. /// Get the number of threads in the thread pool.
  1146. /// Should be between the lower and the upper limits.
  1147. /// </summary>
  1148. public int ActiveThreads
  1149. {
  1150. get
  1151. {
  1152. ValidateNotDisposed();
  1153. return _workerThreads.Count;
  1154. }
  1155. }
  1156. /// <summary>
  1157. /// Get the number of busy (not idle) threads in the thread pool.
  1158. /// </summary>
  1159. public int InUseThreads
  1160. {
  1161. get
  1162. {
  1163. ValidateNotDisposed();
  1164. return _inUseWorkerThreads;
  1165. }
  1166. }
  1167. /// <summary>
  1168. /// Returns true if the current running work item has been cancelled.
  1169. /// Must be used within the work item's callback method.
  1170. /// The work item should sample this value in order to know if it
  1171. /// needs to quit before its completion.
  1172. /// </summary>
  1173. public static bool IsWorkItemCanceled
  1174. {
  1175. get
  1176. {
  1177. return CurrentThreadEntry.CurrentWorkItem.IsCanceled;
  1178. }
  1179. }
  1180. /// <summary>
  1181. /// Checks if the work item has been cancelled, and if yes then abort the thread.
  1182. /// Can be used with Cancel and timeout
  1183. /// </summary>
  1184. public static void AbortOnWorkItemCancel()
  1185. {
  1186. if (IsWorkItemCanceled)
  1187. {
  1188. Thread.CurrentThread.Abort();
  1189. }
  1190. }
  1191. /// <summary>
  1192. /// Thread Pool start information (readonly)
  1193. /// </summary>
  1194. public STPStartInfo STPStartInfo
  1195. {
  1196. get
  1197. {
  1198. return _stpStartInfo.AsReadOnly();
  1199. }
  1200. }
  1201. public bool IsShuttingdown
  1202. {
  1203. get { return _shutdown; }
  1204. }
  1205. /// <summary>
  1206. /// Return the local calculated performance counters
  1207. /// Available only if STPStartInfo.EnableLocalPerformanceCounters is true.
  1208. /// </summary>
  1209. public ISTPPerformanceCountersReader PerformanceCountersReader
  1210. {
  1211. get { return (ISTPPerformanceCountersReader)_localPCs; }
  1212. }
  1213. #endregion
  1214. #region IDisposable Members
  1215. public void Dispose()
  1216. {
  1217. Dispose(true);
  1218. GC.SuppressFinalize(this);
  1219. }
  1220. protected void Dispose(bool disposing)
  1221. {
  1222. if (!_isDisposed)
  1223. {
  1224. if (!_shutdown)
  1225. {
  1226. Shutdown();
  1227. }
  1228. if (null != _shuttingDownEvent)
  1229. {
  1230. _shuttingDownEvent.Close();
  1231. _shuttingDownEvent = null;
  1232. }
  1233. _workerThreads.Clear();
  1234. if (null != _isIdleWaitHandle)
  1235. {
  1236. _isIdleWaitHandle.Close();
  1237. _isIdleWaitHandle = null;
  1238. }
  1239. if (_stpStartInfo.EnableLocalPerformanceCounters)
  1240. _localPCs.Dispose();
  1241. _isDisposed = true;
  1242. }
  1243. }
  1244. private void ValidateNotDisposed()
  1245. {
  1246. if (_isDisposed)
  1247. {
  1248. throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown");
  1249. }
  1250. }
  1251. #endregion
  1252. #region WorkItemsGroupBase Overrides
  1253. /// <summary>
  1254. /// Get/Set the maximum number of work items that execute cocurrency on the thread pool
  1255. /// </summary>
  1256. public override int Concurrency
  1257. {
  1258. get { return MaxThreads; }
  1259. set { MaxThreads = value; }
  1260. }
  1261. /// <summary>
  1262. /// Get the number of work items in the queue.
  1263. /// </summary>
  1264. public override int WaitingCallbacks
  1265. {
  1266. get
  1267. {
  1268. ValidateNotDisposed();
  1269. return _workItemsQueue.Count;
  1270. }
  1271. }
  1272. /// <summary>
  1273. /// Get an array with all the state objects of the currently running items.
  1274. /// The array represents a snap shot and impact performance.
  1275. /// </summary>
  1276. public override object[] GetStates()
  1277. {
  1278. object[] states = _workItemsQueue.GetStates();
  1279. return states;
  1280. }
  1281. /// <summary>
  1282. /// WorkItemsGroup start information (readonly)
  1283. /// </summary>
  1284. public override WIGStartInfo WIGStartInfo
  1285. {
  1286. get { return _stpStartInfo.AsReadOnly(); }
  1287. }
  1288. /// <summary>
  1289. /// Start the thread pool if it was started suspended.
  1290. /// If it is already running, this method is ignored.
  1291. /// </summary>
  1292. public override void Start()
  1293. {
  1294. if (!_isSuspended)
  1295. {
  1296. return;
  1297. }
  1298. _isSuspended = false;
  1299. ICollection workItemsGroups = _workItemsGroups.Values;
  1300. foreach (WorkItemsGroup workItemsGroup in workItemsGroups)
  1301. {
  1302. workItemsGroup.OnSTPIsStarting();
  1303. }
  1304. StartOptimalNumberOfThreads();
  1305. }
  1306. /// <summary>
  1307. /// Cancel all work items using thread abortion
  1308. /// </summary>
  1309. /// <param name="abortExecution">True to stop work items by raising ThreadAbortException</param>
  1310. public override void Cancel(bool abortExecution)
  1311. {
  1312. _canceledSmartThreadPool.IsCanceled = true;
  1313. _canceledSmartThreadPool = new CanceledWorkItemsGroup();
  1314. ICollection workItemsGroups = _workItemsGroups.Values;
  1315. foreach (WorkItemsGroup workItemsGroup in workItemsGroups)
  1316. {
  1317. workItemsGroup.Cancel(abortExecution);
  1318. }
  1319. if (abortExecution)
  1320. {
  1321. foreach (ThreadEntry threadEntry in _workerThreads.Values)
  1322. {
  1323. WorkItem workItem = threadEntry.CurrentWorkItem;
  1324. if (null != workItem &&
  1325. threadEntry.AssociatedSmartThreadPool == this &&
  1326. !workItem.IsCanceled)
  1327. {
  1328. threadEntry.CurrentWorkItem.GetWorkItemResult().Cancel(true);
  1329. }
  1330. }
  1331. }
  1332. }
  1333. /// <summary>
  1334. /// Wait for the thread pool to be idle
  1335. /// </summary>
  1336. public override bool WaitForIdle(int millisecondsTimeout)
  1337. {
  1338. ValidateWaitForIdle();
  1339. return STPEventWaitHandle.WaitOne(_isIdleWaitHandle, millisecondsTimeout, false);
  1340. }
  1341. /// <summary>
  1342. /// This event is fired when all work items are completed.
  1343. /// (When IsIdle changes to true)
  1344. /// This event only work on WorkItemsGroup. On SmartThreadPool
  1345. /// it throws the NotImplementedException.
  1346. /// </summary>
  1347. public override event WorkItemsGroupIdleHandler OnIdle
  1348. {
  1349. add
  1350. {
  1351. //_onIdle += value;
  1352. }
  1353. remove
  1354. {
  1355. //_onIdle -= value;
  1356. }
  1357. }
  1358. internal override void PreQueueWorkItem()
  1359. {
  1360. ValidateNotDisposed();
  1361. }
  1362. #endregion
  1363. #region Join, Choice, Pipe, etc.
  1364. /// <summary>
  1365. /// Executes all actions in parallel.
  1366. /// Returns when they all finish.
  1367. /// </summary>
  1368. /// <param name="actions">Actions to execute</param>
  1369. public void Join(IEnumerable<Action> actions)
  1370. {
  1371. WIGStartInfo wigStartInfo = new WIGStartInfo { StartSuspended = true };
  1372. IWorkItemsGroup workItemsGroup = CreateWorkItemsGroup(int.MaxValue, wigStartInfo);
  1373. foreach (Action action in actions)
  1374. {
  1375. workItemsGroup.QueueWorkItem(action);
  1376. }
  1377. workItemsGroup.Start();
  1378. workItemsGroup.WaitForIdle();
  1379. }
  1380. /// <summary>
  1381. /// Executes all actions in parallel.
  1382. /// Returns when they all finish.
  1383. /// </summary>
  1384. /// <param name="actions">Actions to execute</param>
  1385. public void Join(params Action[] actions)
  1386. {
  1387. Join((IEnumerable<Action>)actions);
  1388. }
  1389. private class ChoiceIndex
  1390. {
  1391. public int _index = -1;
  1392. }
  1393. /// <summary>
  1394. /// Executes all actions in parallel
  1395. /// Returns when the first one completes
  1396. /// </summary>
  1397. /// <param name="actions">Actions to execute</param>
  1398. public int Choice(IEnumerable<Action> actions)
  1399. {
  1400. WIGStartInfo wigStartInfo = new WIGStartInfo { StartSuspended = true };
  1401. IWorkItemsGroup workItemsGroup = CreateWorkItemsGroup(int.MaxValue, wigStartInfo);
  1402. ManualResetEvent anActionCompleted = new ManualResetEvent(false);
  1403. ChoiceIndex choiceIndex = new ChoiceIndex();
  1404. int i = 0;
  1405. foreach (Action action in actions)
  1406. {
  1407. Action act = action;
  1408. int value = i;
  1409. workItemsGroup.QueueWorkItem(() => { act(); Interlocked.CompareExchange(ref choiceIndex._index, value, -1); anActionCompleted.Set(); });
  1410. ++i;
  1411. }
  1412. workItemsGroup.Start();
  1413. anActionCompleted.WaitOne();
  1414. anActionCompleted.Dispose();
  1415. return choiceIndex._index;
  1416. }
  1417. /// <summary>
  1418. /// Executes all actions in parallel
  1419. /// Returns when the first one completes
  1420. /// </summary>
  1421. /// <param name="actions">Actions to execute</param>
  1422. public int Choice(params Action[] actions)
  1423. {
  1424. return Choice((IEnumerable<Action>)actions);
  1425. }
  1426. /// <summary>
  1427. /// Executes actions in sequence asynchronously.
  1428. /// Returns immediately.
  1429. /// </summary>
  1430. /// <param name="pipeState">A state context that passes </param>
  1431. /// <param name="actions">Actions to execute in the order they should run</param>
  1432. public void Pipe<T>(T pipeState, IEnumerable<Action<T>> actions)
  1433. {
  1434. WIGStartInfo wigStartInfo = new WIGStartInfo { StartSuspended = true };
  1435. IWorkItemsGroup workItemsGroup = CreateWorkItemsGroup(1, wigStartInfo);
  1436. foreach (Action<T> action in actions)
  1437. {
  1438. Action<T> act = action;
  1439. workItemsGroup.QueueWorkItem(() => act(pipeState));
  1440. }
  1441. workItemsGroup.Start();
  1442. workItemsGroup.WaitForIdle();
  1443. }
  1444. /// <summary>
  1445. /// Executes actions in sequence asynchronously.
  1446. /// Returns immediately.
  1447. /// </summary>
  1448. /// <param name="pipeState"></param>
  1449. /// <param name="actions">Actions to execute in the order they should run</param>
  1450. public void Pipe<T>(T pipeState, params Action<T>[] actions)
  1451. {
  1452. Pipe(pipeState, (IEnumerable<Action<T>>)actions);
  1453. }
  1454. #endregion
  1455. }
  1456. #endregion
  1457. }