SmartThreadPool.cs 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  1. // Ami Bar
  2. // [email protected]
  3. //
  4. // Smart thread pool in C#.
  5. // 7 Aug 2004 - Initial release
  6. // 14 Sep 2004 - Bug fixes
  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. // 26 Dec 2004 - Changes:
  15. // - Removed static constructors.
  16. // - Added finalizers.
  17. // - Changed Exceptions so they are serializable.
  18. // - Fixed the bug in one of the SmartThreadPool constructors.
  19. // - Changed the SmartThreadPool.WaitAll() so it will support any number of waiters.
  20. // The SmartThreadPool.WaitAny() is still limited by the .NET Framework.
  21. // - Added PostExecute with options on which cases to call it.
  22. // - Added option to dispose of the state objects.
  23. // - Added a WaitForIdle() method that waits until the work items queue is empty.
  24. // - Added an STPStartInfo class for the initialization of the thread pool.
  25. // - Changed exception handling so if a work item throws an exception it
  26. // is rethrown at GetResult(), rather then firing an UnhandledException event.
  27. // Note that PostExecute exception are always ignored.
  28. // 25 Mar 2005 - Changes:
  29. // - Fixed lost of work items bug
  30. // 3 Jul 2005: Changes.
  31. // - Fixed bug where Enqueue() throws an exception because PopWaiter() returned null, hardly reconstructed.
  32. // 16 Aug 2005: Changes.
  33. // - Fixed bug where the InUseThreads becomes negative when canceling work items.
  34. //
  35. // 31 Jan 2006 - Changes:
  36. // - Added work items priority
  37. // - Removed support of chained delegates in callbacks and post executes (nobody really use this)
  38. // - Added work items groups
  39. // - Added work items groups idle event
  40. // - Changed SmartThreadPool.WaitAll() behavior so when it gets empty array
  41. // it returns true rather then throwing an exception.
  42. // - Added option to start the STP and the WIG as suspended
  43. // - Exception behavior changed, the real exception is returned by an
  44. // inner exception
  45. // - Added option to keep the Http context of the caller thread. (Thanks to Steven T.)
  46. // - Added performance counters
  47. // - Added priority to the threads in the pool
  48. //
  49. // 13 Feb 2006 - Changes:
  50. // - Added a call to the dispose of the Performance Counter so
  51. // their won't be a Performance Counter leak.
  52. // - Added exception catch in case the Performance Counters cannot
  53. // be created.
  54. using System;
  55. using System.Security;
  56. using System.Threading;
  57. using System.Collections;
  58. using System.Diagnostics;
  59. using System.Runtime.CompilerServices;
  60. using Amib.Threading.Internal;
  61. namespace Amib.Threading
  62. {
  63. #region SmartThreadPool class
  64. /// <summary>
  65. /// Smart thread pool class.
  66. /// </summary>
  67. public class SmartThreadPool : IWorkItemsGroup, IDisposable
  68. {
  69. #region Default Constants
  70. /// <summary>
  71. /// Default minimum number of threads the thread pool contains. (0)
  72. /// </summary>
  73. public const int DefaultMinWorkerThreads = 0;
  74. /// <summary>
  75. /// Default maximum number of threads the thread pool contains. (25)
  76. /// </summary>
  77. public const int DefaultMaxWorkerThreads = 25;
  78. /// <summary>
  79. /// Default idle timeout in milliseconds. (One minute)
  80. /// </summary>
  81. public const int DefaultIdleTimeout = 60*1000; // One minute
  82. /// <summary>
  83. /// Indicate to copy the security context of the caller and then use it in the call. (false)
  84. /// </summary>
  85. public const bool DefaultUseCallerCallContext = false;
  86. /// <summary>
  87. /// Indicate to copy the HTTP context of the caller and then use it in the call. (false)
  88. /// </summary>
  89. public const bool DefaultUseCallerHttpContext = false;
  90. /// <summary>
  91. /// Indicate to dispose of the state objects if they support the IDispose interface. (false)
  92. /// </summary>
  93. public const bool DefaultDisposeOfStateObjects = false;
  94. /// <summary>
  95. /// The default option to run the post execute
  96. /// </summary>
  97. public const CallToPostExecute DefaultCallToPostExecute = CallToPostExecute.Always;
  98. /// <summary>
  99. /// The default post execute method to run.
  100. /// When null it means not to call it.
  101. /// </summary>
  102. public static readonly PostExecuteWorkItemCallback DefaultPostExecuteWorkItemCallback = null;
  103. /// <summary>
  104. /// The default work item priority
  105. /// </summary>
  106. public const WorkItemPriority DefaultWorkItemPriority = WorkItemPriority.Normal;
  107. /// <summary>
  108. /// The default is to work on work items as soon as they arrive
  109. /// and not to wait for the start.
  110. /// </summary>
  111. public const bool DefaultStartSuspended = false;
  112. /// <summary>
  113. /// The default is not to use the performance counters
  114. /// </summary>
  115. public static readonly string DefaultPerformanceCounterInstanceName = null;
  116. public static readonly int DefaultStackSize = 0;
  117. /// <summary>
  118. /// The default thread priority
  119. /// </summary>
  120. public const ThreadPriority DefaultThreadPriority = ThreadPriority.Normal;
  121. #endregion
  122. #region Member Variables
  123. /// <summary>
  124. /// Contains the name of this instance of SmartThreadPool.
  125. /// Can be changed by the user.
  126. /// </summary>
  127. private string _name = "SmartThreadPool";
  128. /// <summary>
  129. /// Hashtable of all the threads in the thread pool.
  130. /// </summary>
  131. private Hashtable _workerThreads = Hashtable.Synchronized(new Hashtable());
  132. /// <summary>
  133. /// Queue of work items.
  134. /// </summary>
  135. private WorkItemsQueue _workItemsQueue = new WorkItemsQueue();
  136. /// <summary>
  137. /// Count the work items handled.
  138. /// Used by the performance counter.
  139. /// </summary>
  140. private long _workItemsProcessed = 0;
  141. /// <summary>
  142. /// Number of threads that currently work (not idle).
  143. /// </summary>
  144. private int _inUseWorkerThreads = 0;
  145. /// <summary>
  146. /// Start information to use.
  147. /// It is simpler than providing many constructors.
  148. /// </summary>
  149. private STPStartInfo _stpStartInfo = new STPStartInfo();
  150. /// <summary>
  151. /// Total number of work items that are stored in the work items queue
  152. /// plus the work items that the threads in the pool are working on.
  153. /// </summary>
  154. private int _currentWorkItemsCount = 0;
  155. /// <summary>
  156. /// Signaled when the thread pool is idle, i.e. no thread is busy
  157. /// and the work items queue is empty
  158. /// </summary>
  159. private ManualResetEvent _isIdleWaitHandle = new ManualResetEvent(true);
  160. /// <summary>
  161. /// An event to signal all the threads to quit immediately.
  162. /// </summary>
  163. private ManualResetEvent _shuttingDownEvent = new ManualResetEvent(false);
  164. /// <summary>
  165. /// A flag to indicate the threads to quit.
  166. /// </summary>
  167. private bool _shutdown = false;
  168. /// <summary>
  169. /// Counts the threads created in the pool.
  170. /// It is used to name the threads.
  171. /// </summary>
  172. private int _threadCounter = 0;
  173. /// <summary>
  174. /// Indicate that the SmartThreadPool has been disposed
  175. /// </summary>
  176. private bool _isDisposed = false;
  177. /// <summary>
  178. /// Event to send that the thread pool is idle
  179. /// </summary>
  180. private event EventHandler _stpIdle;
  181. /// <summary>
  182. /// On idle event
  183. /// </summary>
  184. //private event WorkItemsGroupIdleHandler _onIdle;
  185. /// <summary>
  186. /// Holds all the WorkItemsGroup instaces that have at least one
  187. /// work item int the SmartThreadPool
  188. /// This variable is used in case of Shutdown
  189. /// </summary>
  190. private Hashtable _workItemsGroups = Hashtable.Synchronized(new Hashtable());
  191. /// <summary>
  192. /// A reference from each thread in the thread pool to its SmartThreadPool
  193. /// object container.
  194. /// With this variable a thread can know whatever it belongs to a
  195. /// SmartThreadPool.
  196. /// </summary>
  197. [ThreadStatic]
  198. private static SmartThreadPool _smartThreadPool;
  199. /// <summary>
  200. /// A reference to the current work item a thread from the thread pool
  201. /// is executing.
  202. /// </summary>
  203. [ThreadStatic]
  204. private static WorkItem _currentWorkItem;
  205. /// <summary>
  206. /// STP performance counters
  207. /// </summary>
  208. private ISTPInstancePerformanceCounters _pcs = NullSTPInstancePerformanceCounters.Instance;
  209. #endregion
  210. #region Construction and Finalization
  211. /// <summary>
  212. /// Constructor
  213. /// </summary>
  214. public SmartThreadPool()
  215. {
  216. Initialize();
  217. }
  218. /// <summary>
  219. /// Constructor
  220. /// </summary>
  221. /// <param name="idleTimeout">Idle timeout in milliseconds</param>
  222. public SmartThreadPool(int idleTimeout)
  223. {
  224. _stpStartInfo.IdleTimeout = idleTimeout;
  225. Initialize();
  226. }
  227. /// <summary>
  228. /// Constructor
  229. /// </summary>
  230. /// <param name="idleTimeout">Idle timeout in milliseconds</param>
  231. /// <param name="maxWorkerThreads">Upper limit of threads in the pool</param>
  232. public SmartThreadPool(
  233. int idleTimeout,
  234. int maxWorkerThreads)
  235. {
  236. _stpStartInfo.IdleTimeout = idleTimeout;
  237. _stpStartInfo.MaxWorkerThreads = maxWorkerThreads;
  238. Initialize();
  239. }
  240. /// <summary>
  241. /// Constructor
  242. /// </summary>
  243. /// <param name="idleTimeout">Idle timeout in milliseconds</param>
  244. /// <param name="maxWorkerThreads">Upper limit of threads in the pool</param>
  245. /// <param name="minWorkerThreads">Lower limit of threads in the pool</param>
  246. public SmartThreadPool(
  247. int idleTimeout,
  248. int maxWorkerThreads,
  249. int minWorkerThreads)
  250. {
  251. _stpStartInfo.IdleTimeout = idleTimeout;
  252. _stpStartInfo.MaxWorkerThreads = maxWorkerThreads;
  253. _stpStartInfo.MinWorkerThreads = minWorkerThreads;
  254. Initialize();
  255. }
  256. /// <summary>
  257. /// Constructor
  258. /// </summary>
  259. public SmartThreadPool(STPStartInfo stpStartInfo)
  260. {
  261. _stpStartInfo = new STPStartInfo(stpStartInfo);
  262. Initialize();
  263. }
  264. private void Initialize()
  265. {
  266. ValidateSTPStartInfo();
  267. if (null != _stpStartInfo.PerformanceCounterInstanceName)
  268. {
  269. try
  270. {
  271. _pcs = new STPInstancePerformanceCounters(_stpStartInfo.PerformanceCounterInstanceName);
  272. }
  273. catch(Exception e)
  274. {
  275. Debug.WriteLine("Unable to create Performance Counters: " + e.ToString());
  276. _pcs = NullSTPInstancePerformanceCounters.Instance;
  277. }
  278. }
  279. StartOptimalNumberOfThreads();
  280. }
  281. private void StartOptimalNumberOfThreads()
  282. {
  283. int threadsCount = Math.Max(_workItemsQueue.Count, _stpStartInfo.MinWorkerThreads);
  284. threadsCount = Math.Min(threadsCount, _stpStartInfo.MaxWorkerThreads);
  285. StartThreads(threadsCount);
  286. }
  287. private void ValidateSTPStartInfo()
  288. {
  289. if (_stpStartInfo.MinWorkerThreads < 0)
  290. {
  291. throw new ArgumentOutOfRangeException(
  292. "MinWorkerThreads", "MinWorkerThreads cannot be negative");
  293. }
  294. if (_stpStartInfo.MaxWorkerThreads <= 0)
  295. {
  296. throw new ArgumentOutOfRangeException(
  297. "MaxWorkerThreads", "MaxWorkerThreads must be greater than zero");
  298. }
  299. if (_stpStartInfo.MinWorkerThreads > _stpStartInfo.MaxWorkerThreads)
  300. {
  301. throw new ArgumentOutOfRangeException(
  302. "MinWorkerThreads, maxWorkerThreads",
  303. "MaxWorkerThreads must be greater or equal to MinWorkerThreads");
  304. }
  305. }
  306. private void ValidateCallback(Delegate callback)
  307. {
  308. if(callback.GetInvocationList().Length > 1)
  309. {
  310. throw new NotSupportedException("SmartThreadPool doesn't support delegates chains");
  311. }
  312. }
  313. #endregion
  314. #region Thread Processing
  315. /// <summary>
  316. /// Waits on the queue for a work item, shutdown, or timeout.
  317. /// </summary>
  318. /// <returns>
  319. /// Returns the WaitingCallback or null in case of timeout or shutdown.
  320. /// </returns>
  321. private WorkItem Dequeue()
  322. {
  323. WorkItem workItem =
  324. _workItemsQueue.DequeueWorkItem(_stpStartInfo.IdleTimeout, _shuttingDownEvent);
  325. return workItem;
  326. }
  327. /// <summary>
  328. /// Put a new work item in the queue
  329. /// </summary>
  330. /// <param name="workItem">A work item to queue</param>
  331. private void Enqueue(WorkItem workItem)
  332. {
  333. Enqueue(workItem, true);
  334. }
  335. /// <summary>
  336. /// Put a new work item in the queue
  337. /// </summary>
  338. /// <param name="workItem">A work item to queue</param>
  339. internal void Enqueue(WorkItem workItem, bool incrementWorkItems)
  340. {
  341. // Make sure the workItem is not null
  342. Debug.Assert(null != workItem);
  343. if (incrementWorkItems)
  344. {
  345. IncrementWorkItemsCount();
  346. }
  347. _workItemsQueue.EnqueueWorkItem(workItem);
  348. workItem.WorkItemIsQueued();
  349. // If all the threads are busy then try to create a new one
  350. if ((InUseThreads + WaitingCallbacks) > _workerThreads.Count)
  351. {
  352. StartThreads(1);
  353. }
  354. }
  355. private void IncrementWorkItemsCount()
  356. {
  357. _pcs.SampleWorkItems(_workItemsQueue.Count, _workItemsProcessed);
  358. int count = Interlocked.Increment(ref _currentWorkItemsCount);
  359. //Trace.WriteLine("WorkItemsCount = " + _currentWorkItemsCount.ToString());
  360. if (count == 1)
  361. {
  362. //Trace.WriteLine("STP is NOT idle");
  363. _isIdleWaitHandle.Reset();
  364. }
  365. }
  366. private void DecrementWorkItemsCount()
  367. {
  368. ++_workItemsProcessed;
  369. // The counter counts even if the work item was cancelled
  370. _pcs.SampleWorkItems(_workItemsQueue.Count, _workItemsProcessed);
  371. int count = Interlocked.Decrement(ref _currentWorkItemsCount);
  372. //Trace.WriteLine("WorkItemsCount = " + _currentWorkItemsCount.ToString());
  373. if (count == 0)
  374. {
  375. //Trace.WriteLine("STP is idle");
  376. _isIdleWaitHandle.Set();
  377. }
  378. }
  379. internal void RegisterWorkItemsGroup(IWorkItemsGroup workItemsGroup)
  380. {
  381. _workItemsGroups[workItemsGroup] = workItemsGroup;
  382. }
  383. internal void UnregisterWorkItemsGroup(IWorkItemsGroup workItemsGroup)
  384. {
  385. if (_workItemsGroups.Contains(workItemsGroup))
  386. {
  387. _workItemsGroups.Remove(workItemsGroup);
  388. }
  389. }
  390. /// <summary>
  391. /// Inform that the current thread is about to quit or quiting.
  392. /// The same thread may call this method more than once.
  393. /// </summary>
  394. private void InformCompleted()
  395. {
  396. // There is no need to lock the two methods together
  397. // since only the current thread removes itself
  398. // and the _workerThreads is a synchronized hashtable
  399. if (_workerThreads.Contains(Thread.CurrentThread))
  400. {
  401. _workerThreads.Remove(Thread.CurrentThread);
  402. _pcs.SampleThreads(_workerThreads.Count, _inUseWorkerThreads);
  403. }
  404. }
  405. /// <summary>
  406. /// Starts new threads
  407. /// </summary>
  408. /// <param name="threadsCount">The number of threads to start</param>
  409. private void StartThreads(int threadsCount)
  410. {
  411. if (_stpStartInfo.StartSuspended)
  412. {
  413. return;
  414. }
  415. lock(_workerThreads.SyncRoot)
  416. {
  417. // Don't start threads on shut down
  418. if (_shutdown)
  419. {
  420. return;
  421. }
  422. for(int i = 0; i < threadsCount; ++i)
  423. {
  424. // Don't create more threads then the upper limit
  425. if (_workerThreads.Count >= _stpStartInfo.MaxWorkerThreads)
  426. {
  427. return;
  428. }
  429. // Create a new thread
  430. Thread workerThread = new Thread(new ThreadStart(ProcessQueuedItems), _stpStartInfo.StackSize);
  431. // Configure the new thread and start it
  432. workerThread.Name = "STP " + Name + " Thread #" + _threadCounter;
  433. workerThread.IsBackground = true;
  434. workerThread.Priority = _stpStartInfo.ThreadPriority;
  435. workerThread.Start();
  436. ++_threadCounter;
  437. // Add the new thread to the hashtable and update its creation
  438. // time.
  439. _workerThreads[workerThread] = DateTime.Now;
  440. _pcs.SampleThreads(_workerThreads.Count, _inUseWorkerThreads);
  441. }
  442. }
  443. }
  444. /// <summary>
  445. /// A worker thread method that processes work items from the work items queue.
  446. /// </summary>
  447. private void ProcessQueuedItems()
  448. {
  449. // Initialize the _smartThreadPool variable
  450. _smartThreadPool = this;
  451. try
  452. {
  453. bool bInUseWorkerThreadsWasIncremented = false;
  454. // Process until shutdown.
  455. while(!_shutdown)
  456. {
  457. // Update the last time this thread was seen alive.
  458. // It's good for debugging.
  459. _workerThreads[Thread.CurrentThread] = DateTime.Now;
  460. // Wait for a work item, shutdown, or timeout
  461. WorkItem workItem = Dequeue();
  462. // Update the last time this thread was seen alive.
  463. // It's good for debugging.
  464. _workerThreads[Thread.CurrentThread] = DateTime.Now;
  465. // On timeout or shut down.
  466. if (null == workItem)
  467. {
  468. // Double lock for quit.
  469. if (_workerThreads.Count > _stpStartInfo.MinWorkerThreads)
  470. {
  471. lock(_workerThreads.SyncRoot)
  472. {
  473. if (_workerThreads.Count > _stpStartInfo.MinWorkerThreads)
  474. {
  475. // Inform that the thread is quiting and then quit.
  476. // This method must be called within this lock or else
  477. // more threads will quit and the thread pool will go
  478. // below the lower limit.
  479. InformCompleted();
  480. break;
  481. }
  482. }
  483. }
  484. }
  485. // If we didn't quit then skip to the next iteration.
  486. if (null == workItem)
  487. {
  488. continue;
  489. }
  490. try
  491. {
  492. // Initialize the value to false
  493. bInUseWorkerThreadsWasIncremented = false;
  494. // Change the state of the work item to 'in progress' if possible.
  495. // We do it here so if the work item has been canceled we won't
  496. // increment the _inUseWorkerThreads.
  497. // The cancel mechanism doesn't delete items from the queue,
  498. // it marks the work item as canceled, and when the work item
  499. // is dequeued, we just skip it.
  500. // If the post execute of work item is set to always or to
  501. // call when the work item is canceled then the StartingWorkItem()
  502. // will return true, so the post execute can run.
  503. if (!workItem.StartingWorkItem())
  504. {
  505. continue;
  506. }
  507. // Execute the callback. Make sure to accurately
  508. // record how many callbacks are currently executing.
  509. int inUseWorkerThreads = Interlocked.Increment(ref _inUseWorkerThreads);
  510. _pcs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  511. // Mark that the _inUseWorkerThreads incremented, so in the finally{}
  512. // statement we will decrement it correctly.
  513. bInUseWorkerThreadsWasIncremented = true;
  514. // Set the _currentWorkItem to the current work item
  515. _currentWorkItem = workItem;
  516. lock(workItem)
  517. {
  518. workItem.currentThread = Thread.CurrentThread;
  519. }
  520. ExecuteWorkItem(workItem);
  521. lock(workItem)
  522. {
  523. workItem.currentThread = null;
  524. }
  525. }
  526. catch(ThreadAbortException ex)
  527. {
  528. lock(workItem)
  529. {
  530. workItem.currentThread = null;
  531. }
  532. ex.GetHashCode();
  533. Thread.ResetAbort();
  534. }
  535. catch(Exception ex)
  536. {
  537. ex.GetHashCode();
  538. // Do nothing
  539. }
  540. finally
  541. {
  542. lock(workItem)
  543. {
  544. workItem.currentThread = null;
  545. }
  546. if (null != workItem)
  547. {
  548. workItem.DisposeOfState();
  549. }
  550. // Set the _currentWorkItem to null, since we
  551. // no longer run user's code.
  552. _currentWorkItem = null;
  553. // Decrement the _inUseWorkerThreads only if we had
  554. // incremented it. Note the cancelled work items don't
  555. // increment _inUseWorkerThreads.
  556. if (bInUseWorkerThreadsWasIncremented)
  557. {
  558. int inUseWorkerThreads = Interlocked.Decrement(ref _inUseWorkerThreads);
  559. _pcs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  560. }
  561. // Notify that the work item has been completed.
  562. // WorkItemsGroup may enqueue their next work item.
  563. workItem.FireWorkItemCompleted();
  564. // Decrement the number of work items here so the idle
  565. // ManualResetEvent won't fluctuate.
  566. DecrementWorkItemsCount();
  567. }
  568. }
  569. }
  570. catch(ThreadAbortException tae)
  571. {
  572. tae.GetHashCode();
  573. // Handle the abort exception gracfully.
  574. Thread.ResetAbort();
  575. }
  576. catch(Exception e)
  577. {
  578. Debug.Assert(null != e);
  579. }
  580. finally
  581. {
  582. InformCompleted();
  583. }
  584. }
  585. private void ExecuteWorkItem(WorkItem workItem)
  586. {
  587. _pcs.SampleWorkItemsWaitTime(workItem.WaitingTime);
  588. try
  589. {
  590. workItem.Execute();
  591. }
  592. catch
  593. {
  594. throw;
  595. }
  596. finally
  597. {
  598. _pcs.SampleWorkItemsProcessTime(workItem.ProcessTime);
  599. }
  600. }
  601. #endregion
  602. #region Public Methods
  603. /// <summary>
  604. /// Queue a work item
  605. /// </summary>
  606. /// <param name="callback">A callback to execute</param>
  607. /// <returns>Returns a work item result</returns>
  608. public IWorkItemResult QueueWorkItem(WorkItemCallback callback)
  609. {
  610. ValidateNotDisposed();
  611. ValidateCallback(callback);
  612. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback);
  613. Enqueue(workItem);
  614. return workItem.GetWorkItemResult();
  615. }
  616. /// <summary>
  617. /// Queue a work item
  618. /// </summary>
  619. /// <param name="callback">A callback to execute</param>
  620. /// <param name="workItemPriority">The priority of the work item</param>
  621. /// <returns>Returns a work item result</returns>
  622. public IWorkItemResult QueueWorkItem(WorkItemCallback callback, WorkItemPriority workItemPriority)
  623. {
  624. ValidateNotDisposed();
  625. ValidateCallback(callback);
  626. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, workItemPriority);
  627. Enqueue(workItem);
  628. return workItem.GetWorkItemResult();
  629. }
  630. /// <summary>
  631. /// Queue a work item
  632. /// </summary>
  633. /// <param name="workItemInfo">Work item info</param>
  634. /// <param name="callback">A callback to execute</param>
  635. /// <returns>Returns a work item result</returns>
  636. public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback)
  637. {
  638. ValidateNotDisposed();
  639. ValidateCallback(callback);
  640. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, workItemInfo, callback);
  641. Enqueue(workItem);
  642. return workItem.GetWorkItemResult();
  643. }
  644. /// <summary>
  645. /// Queue a work item
  646. /// </summary>
  647. /// <param name="callback">A callback to execute</param>
  648. /// <param name="state">
  649. /// The context object of the work item. Used for passing arguments to the work item.
  650. /// </param>
  651. /// <returns>Returns a work item result</returns>
  652. public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state)
  653. {
  654. ValidateNotDisposed();
  655. ValidateCallback(callback);
  656. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state);
  657. Enqueue(workItem);
  658. return workItem.GetWorkItemResult();
  659. }
  660. /// <summary>
  661. /// Queue a work item
  662. /// </summary>
  663. /// <param name="callback">A callback to execute</param>
  664. /// <param name="state">
  665. /// The context object of the work item. Used for passing arguments to the work item.
  666. /// </param>
  667. /// <param name="workItemPriority">The work item priority</param>
  668. /// <returns>Returns a work item result</returns>
  669. public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, WorkItemPriority workItemPriority)
  670. {
  671. ValidateNotDisposed();
  672. ValidateCallback(callback);
  673. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, workItemPriority);
  674. Enqueue(workItem);
  675. return workItem.GetWorkItemResult();
  676. }
  677. /// <summary>
  678. /// Queue a work item
  679. /// </summary>
  680. /// <param name="workItemInfo">Work item information</param>
  681. /// <param name="callback">A callback to execute</param>
  682. /// <param name="state">
  683. /// The context object of the work item. Used for passing arguments to the work item.
  684. /// </param>
  685. /// <returns>Returns a work item result</returns>
  686. public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state)
  687. {
  688. ValidateNotDisposed();
  689. ValidateCallback(callback);
  690. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, workItemInfo, callback, state);
  691. Enqueue(workItem);
  692. return workItem.GetWorkItemResult();
  693. }
  694. /// <summary>
  695. /// Queue a work item
  696. /// </summary>
  697. /// <param name="callback">A callback to execute</param>
  698. /// <param name="state">
  699. /// The context object of the work item. Used for passing arguments to the work item.
  700. /// </param>
  701. /// <param name="postExecuteWorkItemCallback">
  702. /// A delegate to call after the callback completion
  703. /// </param>
  704. /// <returns>Returns a work item result</returns>
  705. public IWorkItemResult QueueWorkItem(
  706. WorkItemCallback callback,
  707. object state,
  708. PostExecuteWorkItemCallback postExecuteWorkItemCallback)
  709. {
  710. ValidateNotDisposed();
  711. ValidateCallback(callback);
  712. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, postExecuteWorkItemCallback);
  713. Enqueue(workItem);
  714. return workItem.GetWorkItemResult();
  715. }
  716. /// <summary>
  717. /// Queue a work item
  718. /// </summary>
  719. /// <param name="callback">A callback to execute</param>
  720. /// <param name="state">
  721. /// The context object of the work item. Used for passing arguments to the work item.
  722. /// </param>
  723. /// <param name="postExecuteWorkItemCallback">
  724. /// A delegate to call after the callback completion
  725. /// </param>
  726. /// <param name="workItemPriority">The work item priority</param>
  727. /// <returns>Returns a work item result</returns>
  728. public IWorkItemResult QueueWorkItem(
  729. WorkItemCallback callback,
  730. object state,
  731. PostExecuteWorkItemCallback postExecuteWorkItemCallback,
  732. WorkItemPriority workItemPriority)
  733. {
  734. ValidateNotDisposed();
  735. ValidateCallback(callback);
  736. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, postExecuteWorkItemCallback, workItemPriority);
  737. Enqueue(workItem);
  738. return workItem.GetWorkItemResult();
  739. }
  740. /// <summary>
  741. /// Queue a work item
  742. /// </summary>
  743. /// <param name="callback">A callback to execute</param>
  744. /// <param name="state">
  745. /// The context object of the work item. Used for passing arguments to the work item.
  746. /// </param>
  747. /// <param name="postExecuteWorkItemCallback">
  748. /// A delegate to call after the callback completion
  749. /// </param>
  750. /// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
  751. /// <returns>Returns a work item result</returns>
  752. public IWorkItemResult QueueWorkItem(
  753. WorkItemCallback callback,
  754. object state,
  755. PostExecuteWorkItemCallback postExecuteWorkItemCallback,
  756. CallToPostExecute callToPostExecute)
  757. {
  758. ValidateNotDisposed();
  759. ValidateCallback(callback);
  760. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute);
  761. Enqueue(workItem);
  762. return workItem.GetWorkItemResult();
  763. }
  764. /// <summary>
  765. /// Queue a work item
  766. /// </summary>
  767. /// <param name="callback">A callback to execute</param>
  768. /// <param name="state">
  769. /// The context object of the work item. Used for passing arguments to the work item.
  770. /// </param>
  771. /// <param name="postExecuteWorkItemCallback">
  772. /// A delegate to call after the callback completion
  773. /// </param>
  774. /// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
  775. /// <param name="workItemPriority">The work item priority</param>
  776. /// <returns>Returns a work item result</returns>
  777. public IWorkItemResult QueueWorkItem(
  778. WorkItemCallback callback,
  779. object state,
  780. PostExecuteWorkItemCallback postExecuteWorkItemCallback,
  781. CallToPostExecute callToPostExecute,
  782. WorkItemPriority workItemPriority)
  783. {
  784. ValidateNotDisposed();
  785. ValidateCallback(callback);
  786. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute, workItemPriority);
  787. Enqueue(workItem);
  788. return workItem.GetWorkItemResult();
  789. }
  790. /// <summary>
  791. /// Wait for the thread pool to be idle
  792. /// </summary>
  793. public void WaitForIdle()
  794. {
  795. WaitForIdle(Timeout.Infinite);
  796. }
  797. /// <summary>
  798. /// Wait for the thread pool to be idle
  799. /// </summary>
  800. public bool WaitForIdle(TimeSpan timeout)
  801. {
  802. return WaitForIdle((int)timeout.TotalMilliseconds);
  803. }
  804. /// <summary>
  805. /// Wait for the thread pool to be idle
  806. /// </summary>
  807. public bool WaitForIdle(int millisecondsTimeout)
  808. {
  809. ValidateWaitForIdle();
  810. return _isIdleWaitHandle.WaitOne(millisecondsTimeout, false);
  811. }
  812. private void ValidateWaitForIdle()
  813. {
  814. if(_smartThreadPool == this)
  815. {
  816. throw new NotSupportedException(
  817. "WaitForIdle cannot be called from a thread on its SmartThreadPool, it will cause may cause a deadlock");
  818. }
  819. }
  820. internal void ValidateWorkItemsGroupWaitForIdle(IWorkItemsGroup workItemsGroup)
  821. {
  822. ValidateWorkItemsGroupWaitForIdleImpl(workItemsGroup, SmartThreadPool._currentWorkItem);
  823. if ((null != workItemsGroup) &&
  824. (null != SmartThreadPool._currentWorkItem) &&
  825. SmartThreadPool._currentWorkItem.WasQueuedBy(workItemsGroup))
  826. {
  827. throw new NotSupportedException("WaitForIdle cannot be called from a thread on its SmartThreadPool, it will cause may cause a deadlock");
  828. }
  829. }
  830. [MethodImpl(MethodImplOptions.NoInlining)]
  831. private void ValidateWorkItemsGroupWaitForIdleImpl(IWorkItemsGroup workItemsGroup, WorkItem workItem)
  832. {
  833. if ((null != workItemsGroup) &&
  834. (null != workItem) &&
  835. workItem.WasQueuedBy(workItemsGroup))
  836. {
  837. throw new NotSupportedException("WaitForIdle cannot be called from a thread on its SmartThreadPool, it will cause may cause a deadlock");
  838. }
  839. }
  840. /// <summary>
  841. /// Force the SmartThreadPool to shutdown
  842. /// </summary>
  843. public void Shutdown()
  844. {
  845. Shutdown(true, 0);
  846. }
  847. public void Shutdown(bool forceAbort, TimeSpan timeout)
  848. {
  849. Shutdown(forceAbort, (int)timeout.TotalMilliseconds);
  850. }
  851. /// <summary>
  852. /// Empties the queue of work items and abort the threads in the pool.
  853. /// </summary>
  854. public void Shutdown(bool forceAbort, int millisecondsTimeout)
  855. {
  856. ValidateNotDisposed();
  857. ISTPInstancePerformanceCounters pcs = _pcs;
  858. if (NullSTPInstancePerformanceCounters.Instance != _pcs)
  859. {
  860. _pcs.Dispose();
  861. // Set the _pcs to "null" to stop updating the performance
  862. // counters
  863. _pcs = NullSTPInstancePerformanceCounters.Instance;
  864. }
  865. Thread [] threads = null;
  866. lock(_workerThreads.SyncRoot)
  867. {
  868. // Shutdown the work items queue
  869. _workItemsQueue.Dispose();
  870. // Signal the threads to exit
  871. _shutdown = true;
  872. _shuttingDownEvent.Set();
  873. // Make a copy of the threads' references in the pool
  874. threads = new Thread [_workerThreads.Count];
  875. _workerThreads.Keys.CopyTo(threads, 0);
  876. }
  877. int millisecondsLeft = millisecondsTimeout;
  878. DateTime start = DateTime.Now;
  879. bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
  880. bool timeout = false;
  881. // Each iteration we update the time left for the timeout.
  882. foreach(Thread thread in threads)
  883. {
  884. // Join don't work with negative numbers
  885. if (!waitInfinitely && (millisecondsLeft < 0))
  886. {
  887. timeout = true;
  888. break;
  889. }
  890. // Wait for the thread to terminate
  891. bool success = thread.Join(millisecondsLeft);
  892. if(!success)
  893. {
  894. timeout = true;
  895. break;
  896. }
  897. if(!waitInfinitely)
  898. {
  899. // Update the time left to wait
  900. TimeSpan ts = DateTime.Now - start;
  901. millisecondsLeft = millisecondsTimeout - (int)ts.TotalMilliseconds;
  902. }
  903. }
  904. if (timeout && forceAbort)
  905. {
  906. // Abort the threads in the pool
  907. foreach(Thread thread in threads)
  908. {
  909. if ((thread != null) && thread.IsAlive)
  910. {
  911. try
  912. {
  913. thread.Abort("Shutdown");
  914. }
  915. catch(SecurityException e)
  916. {
  917. e.GetHashCode();
  918. }
  919. catch(ThreadStateException ex)
  920. {
  921. ex.GetHashCode();
  922. // In case the thread has been terminated
  923. // after the check if it is alive.
  924. }
  925. }
  926. }
  927. }
  928. // Dispose of the performance counters
  929. pcs.Dispose();
  930. }
  931. /// <summary>
  932. /// Wait for all work items to complete
  933. /// </summary>
  934. /// <param name="workItemResults">Array of work item result objects</param>
  935. /// <returns>
  936. /// true when every work item in workItemResults has completed; otherwise false.
  937. /// </returns>
  938. public static bool WaitAll(
  939. IWorkItemResult [] workItemResults)
  940. {
  941. return WaitAll(workItemResults, Timeout.Infinite, true);
  942. }
  943. /// <summary>
  944. /// Wait for all work items to complete
  945. /// </summary>
  946. /// <param name="workItemResults">Array of work item result objects</param>
  947. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  948. /// <param name="exitContext">
  949. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  950. /// </param>
  951. /// <returns>
  952. /// true when every work item in workItemResults has completed; otherwise false.
  953. /// </returns>
  954. public static bool WaitAll(
  955. IWorkItemResult [] workItemResults,
  956. TimeSpan timeout,
  957. bool exitContext)
  958. {
  959. return WaitAll(workItemResults, (int)timeout.TotalMilliseconds, exitContext);
  960. }
  961. /// <summary>
  962. /// Wait for all work items to complete
  963. /// </summary>
  964. /// <param name="workItemResults">Array of work item result objects</param>
  965. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  966. /// <param name="exitContext">
  967. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  968. /// </param>
  969. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  970. /// <returns>
  971. /// true when every work item in workItemResults has completed; otherwise false.
  972. /// </returns>
  973. public static bool WaitAll(
  974. IWorkItemResult [] workItemResults,
  975. TimeSpan timeout,
  976. bool exitContext,
  977. WaitHandle cancelWaitHandle)
  978. {
  979. return WaitAll(workItemResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  980. }
  981. /// <summary>
  982. /// Wait for all work items to complete
  983. /// </summary>
  984. /// <param name="workItemResults">Array of work item result objects</param>
  985. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  986. /// <param name="exitContext">
  987. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  988. /// </param>
  989. /// <returns>
  990. /// true when every work item in workItemResults has completed; otherwise false.
  991. /// </returns>
  992. public static bool WaitAll(
  993. IWorkItemResult [] workItemResults,
  994. int millisecondsTimeout,
  995. bool exitContext)
  996. {
  997. return WorkItem.WaitAll(workItemResults, millisecondsTimeout, exitContext, null);
  998. }
  999. /// <summary>
  1000. /// Wait for all work items to complete
  1001. /// </summary>
  1002. /// <param name="workItemResults">Array of work item result objects</param>
  1003. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  1004. /// <param name="exitContext">
  1005. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1006. /// </param>
  1007. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  1008. /// <returns>
  1009. /// true when every work item in workItemResults has completed; otherwise false.
  1010. /// </returns>
  1011. public static bool WaitAll(
  1012. IWorkItemResult [] workItemResults,
  1013. int millisecondsTimeout,
  1014. bool exitContext,
  1015. WaitHandle cancelWaitHandle)
  1016. {
  1017. return WorkItem.WaitAll(workItemResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  1018. }
  1019. /// <summary>
  1020. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1021. /// </summary>
  1022. /// <param name="workItemResults">Array of work item result objects</param>
  1023. /// <returns>
  1024. /// The array index of the work item result that satisfied the wait, or WaitTimeout if any of the work items has been canceled.
  1025. /// </returns>
  1026. public static int WaitAny(
  1027. IWorkItemResult [] workItemResults)
  1028. {
  1029. return WaitAny(workItemResults, Timeout.Infinite, true);
  1030. }
  1031. /// <summary>
  1032. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1033. /// </summary>
  1034. /// <param name="workItemResults">Array of work item result objects</param>
  1035. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  1036. /// <param name="exitContext">
  1037. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1038. /// </param>
  1039. /// <returns>
  1040. /// 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.
  1041. /// </returns>
  1042. public static int WaitAny(
  1043. IWorkItemResult [] workItemResults,
  1044. TimeSpan timeout,
  1045. bool exitContext)
  1046. {
  1047. return WaitAny(workItemResults, (int)timeout.TotalMilliseconds, exitContext);
  1048. }
  1049. /// <summary>
  1050. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1051. /// </summary>
  1052. /// <param name="workItemResults">Array of work item result objects</param>
  1053. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  1054. /// <param name="exitContext">
  1055. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1056. /// </param>
  1057. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  1058. /// <returns>
  1059. /// 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.
  1060. /// </returns>
  1061. public static int WaitAny(
  1062. IWorkItemResult [] workItemResults,
  1063. TimeSpan timeout,
  1064. bool exitContext,
  1065. WaitHandle cancelWaitHandle)
  1066. {
  1067. return WaitAny(workItemResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  1068. }
  1069. /// <summary>
  1070. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1071. /// </summary>
  1072. /// <param name="workItemResults">Array of work item result objects</param>
  1073. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  1074. /// <param name="exitContext">
  1075. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1076. /// </param>
  1077. /// <returns>
  1078. /// 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.
  1079. /// </returns>
  1080. public static int WaitAny(
  1081. IWorkItemResult [] workItemResults,
  1082. int millisecondsTimeout,
  1083. bool exitContext)
  1084. {
  1085. return WorkItem.WaitAny(workItemResults, millisecondsTimeout, exitContext, null);
  1086. }
  1087. /// <summary>
  1088. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1089. /// </summary>
  1090. /// <param name="workItemResults">Array of work item result objects</param>
  1091. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  1092. /// <param name="exitContext">
  1093. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1094. /// </param>
  1095. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  1096. /// <returns>
  1097. /// 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.
  1098. /// </returns>
  1099. public static int WaitAny(
  1100. IWorkItemResult [] workItemResults,
  1101. int millisecondsTimeout,
  1102. bool exitContext,
  1103. WaitHandle cancelWaitHandle)
  1104. {
  1105. return WorkItem.WaitAny(workItemResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  1106. }
  1107. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency)
  1108. {
  1109. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, _stpStartInfo);
  1110. return workItemsGroup;
  1111. }
  1112. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency, WIGStartInfo wigStartInfo)
  1113. {
  1114. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, wigStartInfo);
  1115. return workItemsGroup;
  1116. }
  1117. public event WorkItemsGroupIdleHandler OnIdle
  1118. {
  1119. add
  1120. {
  1121. throw new NotImplementedException("This event is not implemented in the SmartThreadPool class. Please create a WorkItemsGroup in order to use this feature.");
  1122. //_onIdle += value;
  1123. }
  1124. remove
  1125. {
  1126. throw new NotImplementedException("This event is not implemented in the SmartThreadPool class. Please create a WorkItemsGroup in order to use this feature.");
  1127. //_onIdle -= value;
  1128. }
  1129. }
  1130. public void Cancel()
  1131. {
  1132. ICollection workItemsGroups = _workItemsGroups.Values;
  1133. foreach(WorkItemsGroup workItemsGroup in workItemsGroups)
  1134. {
  1135. workItemsGroup.Cancel();
  1136. }
  1137. }
  1138. public void Start()
  1139. {
  1140. lock (this)
  1141. {
  1142. if (!this._stpStartInfo.StartSuspended)
  1143. {
  1144. return;
  1145. }
  1146. _stpStartInfo.StartSuspended = false;
  1147. }
  1148. ICollection workItemsGroups = _workItemsGroups.Values;
  1149. foreach(WorkItemsGroup workItemsGroup in workItemsGroups)
  1150. {
  1151. workItemsGroup.OnSTPIsStarting();
  1152. }
  1153. StartOptimalNumberOfThreads();
  1154. }
  1155. #endregion
  1156. #region Properties
  1157. /// <summary>
  1158. /// Get/Set the name of the SmartThreadPool instance
  1159. /// </summary>
  1160. public string Name
  1161. {
  1162. get
  1163. {
  1164. return _name;
  1165. }
  1166. set
  1167. {
  1168. _name = value;
  1169. }
  1170. }
  1171. /// <summary>
  1172. /// Get the lower limit of threads in the pool.
  1173. /// </summary>
  1174. public int MinThreads
  1175. {
  1176. get
  1177. {
  1178. ValidateNotDisposed();
  1179. return _stpStartInfo.MinWorkerThreads;
  1180. }
  1181. }
  1182. /// <summary>
  1183. /// Get the upper limit of threads in the pool.
  1184. /// </summary>
  1185. public int MaxThreads
  1186. {
  1187. get
  1188. {
  1189. ValidateNotDisposed();
  1190. return _stpStartInfo.MaxWorkerThreads;
  1191. }
  1192. }
  1193. /// <summary>
  1194. /// Get the number of threads in the thread pool.
  1195. /// Should be between the lower and the upper limits.
  1196. /// </summary>
  1197. public int ActiveThreads
  1198. {
  1199. get
  1200. {
  1201. ValidateNotDisposed();
  1202. return _workerThreads.Count;
  1203. }
  1204. }
  1205. /// <summary>
  1206. /// Get the number of busy (not idle) threads in the thread pool.
  1207. /// </summary>
  1208. public int InUseThreads
  1209. {
  1210. get
  1211. {
  1212. ValidateNotDisposed();
  1213. return _inUseWorkerThreads;
  1214. }
  1215. }
  1216. /// <summary>
  1217. /// Get the number of work items in the queue.
  1218. /// </summary>
  1219. public int WaitingCallbacks
  1220. {
  1221. get
  1222. {
  1223. ValidateNotDisposed();
  1224. return _workItemsQueue.Count;
  1225. }
  1226. }
  1227. public event EventHandler Idle
  1228. {
  1229. add
  1230. {
  1231. _stpIdle += value;
  1232. }
  1233. remove
  1234. {
  1235. _stpIdle -= value;
  1236. }
  1237. }
  1238. #endregion
  1239. #region IDisposable Members
  1240. // ~SmartThreadPool()
  1241. // {
  1242. // Dispose();
  1243. // }
  1244. public void Dispose()
  1245. {
  1246. if (!_isDisposed)
  1247. {
  1248. if (!_shutdown)
  1249. {
  1250. Shutdown();
  1251. }
  1252. if (null != _shuttingDownEvent)
  1253. {
  1254. _shuttingDownEvent.Close();
  1255. _shuttingDownEvent = null;
  1256. }
  1257. _workerThreads.Clear();
  1258. _isDisposed = true;
  1259. GC.SuppressFinalize(this);
  1260. }
  1261. }
  1262. private void ValidateNotDisposed()
  1263. {
  1264. if(_isDisposed)
  1265. {
  1266. throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown");
  1267. }
  1268. }
  1269. #endregion
  1270. }
  1271. #endregion
  1272. }