SmartThreadPool.cs 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  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;
  431. if (_stpStartInfo.StackSize > 0)
  432. workerThread = new Thread(ProcessQueuedItems, _stpStartInfo.StackSize);
  433. else
  434. workerThread = new Thread(ProcessQueuedItems);
  435. // Configure the new thread and start it
  436. workerThread.Name = "STP " + Name + " Thread #" + _threadCounter;
  437. workerThread.IsBackground = true;
  438. workerThread.Priority = _stpStartInfo.ThreadPriority;
  439. workerThread.Start();
  440. ++_threadCounter;
  441. // Add the new thread to the hashtable and update its creation
  442. // time.
  443. _workerThreads[workerThread] = DateTime.Now;
  444. _pcs.SampleThreads(_workerThreads.Count, _inUseWorkerThreads);
  445. }
  446. }
  447. }
  448. /// <summary>
  449. /// A worker thread method that processes work items from the work items queue.
  450. /// </summary>
  451. private void ProcessQueuedItems()
  452. {
  453. // Initialize the _smartThreadPool variable
  454. _smartThreadPool = this;
  455. try
  456. {
  457. bool bInUseWorkerThreadsWasIncremented = false;
  458. // Process until shutdown.
  459. while(!_shutdown)
  460. {
  461. // Update the last time this thread was seen alive.
  462. // It's good for debugging.
  463. _workerThreads[Thread.CurrentThread] = DateTime.Now;
  464. // Wait for a work item, shutdown, or timeout
  465. WorkItem workItem = Dequeue();
  466. // Update the last time this thread was seen alive.
  467. // It's good for debugging.
  468. _workerThreads[Thread.CurrentThread] = DateTime.Now;
  469. // On timeout or shut down.
  470. if (null == workItem)
  471. {
  472. // Double lock for quit.
  473. if (_workerThreads.Count > _stpStartInfo.MinWorkerThreads)
  474. {
  475. lock(_workerThreads.SyncRoot)
  476. {
  477. if (_workerThreads.Count > _stpStartInfo.MinWorkerThreads)
  478. {
  479. // Inform that the thread is quiting and then quit.
  480. // This method must be called within this lock or else
  481. // more threads will quit and the thread pool will go
  482. // below the lower limit.
  483. InformCompleted();
  484. break;
  485. }
  486. }
  487. }
  488. }
  489. // If we didn't quit then skip to the next iteration.
  490. if (null == workItem)
  491. {
  492. continue;
  493. }
  494. try
  495. {
  496. // Initialize the value to false
  497. bInUseWorkerThreadsWasIncremented = false;
  498. // Change the state of the work item to 'in progress' if possible.
  499. // We do it here so if the work item has been canceled we won't
  500. // increment the _inUseWorkerThreads.
  501. // The cancel mechanism doesn't delete items from the queue,
  502. // it marks the work item as canceled, and when the work item
  503. // is dequeued, we just skip it.
  504. // If the post execute of work item is set to always or to
  505. // call when the work item is canceled then the StartingWorkItem()
  506. // will return true, so the post execute can run.
  507. if (!workItem.StartingWorkItem())
  508. {
  509. continue;
  510. }
  511. // Execute the callback. Make sure to accurately
  512. // record how many callbacks are currently executing.
  513. int inUseWorkerThreads = Interlocked.Increment(ref _inUseWorkerThreads);
  514. _pcs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  515. // Mark that the _inUseWorkerThreads incremented, so in the finally{}
  516. // statement we will decrement it correctly.
  517. bInUseWorkerThreadsWasIncremented = true;
  518. // Set the _currentWorkItem to the current work item
  519. _currentWorkItem = workItem;
  520. lock(workItem)
  521. {
  522. workItem.currentThread = Thread.CurrentThread;
  523. }
  524. ExecuteWorkItem(workItem);
  525. lock(workItem)
  526. {
  527. workItem.currentThread = null;
  528. }
  529. }
  530. catch(ThreadAbortException ex)
  531. {
  532. lock(workItem)
  533. {
  534. workItem.currentThread = null;
  535. }
  536. ex.GetHashCode();
  537. Thread.ResetAbort();
  538. }
  539. catch(Exception ex)
  540. {
  541. ex.GetHashCode();
  542. // Do nothing
  543. }
  544. finally
  545. {
  546. lock(workItem)
  547. {
  548. workItem.currentThread = null;
  549. }
  550. if (null != workItem)
  551. {
  552. workItem.DisposeOfState();
  553. }
  554. // Set the _currentWorkItem to null, since we
  555. // no longer run user's code.
  556. _currentWorkItem = null;
  557. // Decrement the _inUseWorkerThreads only if we had
  558. // incremented it. Note the cancelled work items don't
  559. // increment _inUseWorkerThreads.
  560. if (bInUseWorkerThreadsWasIncremented)
  561. {
  562. int inUseWorkerThreads = Interlocked.Decrement(ref _inUseWorkerThreads);
  563. _pcs.SampleThreads(_workerThreads.Count, inUseWorkerThreads);
  564. }
  565. // Notify that the work item has been completed.
  566. // WorkItemsGroup may enqueue their next work item.
  567. workItem.FireWorkItemCompleted();
  568. // Decrement the number of work items here so the idle
  569. // ManualResetEvent won't fluctuate.
  570. DecrementWorkItemsCount();
  571. }
  572. }
  573. }
  574. catch(ThreadAbortException tae)
  575. {
  576. tae.GetHashCode();
  577. // Handle the abort exception gracfully.
  578. Thread.ResetAbort();
  579. }
  580. catch(Exception e)
  581. {
  582. Debug.Assert(null != e);
  583. }
  584. finally
  585. {
  586. InformCompleted();
  587. }
  588. }
  589. private void ExecuteWorkItem(WorkItem workItem)
  590. {
  591. _pcs.SampleWorkItemsWaitTime(workItem.WaitingTime);
  592. try
  593. {
  594. workItem.Execute();
  595. }
  596. catch
  597. {
  598. throw;
  599. }
  600. finally
  601. {
  602. _pcs.SampleWorkItemsProcessTime(workItem.ProcessTime);
  603. }
  604. }
  605. #endregion
  606. #region Public Methods
  607. /// <summary>
  608. /// Queue a work item
  609. /// </summary>
  610. /// <param name="callback">A callback to execute</param>
  611. /// <returns>Returns a work item result</returns>
  612. public IWorkItemResult QueueWorkItem(WorkItemCallback callback)
  613. {
  614. ValidateNotDisposed();
  615. ValidateCallback(callback);
  616. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback);
  617. Enqueue(workItem);
  618. return workItem.GetWorkItemResult();
  619. }
  620. /// <summary>
  621. /// Queue a work item
  622. /// </summary>
  623. /// <param name="callback">A callback to execute</param>
  624. /// <param name="workItemPriority">The priority of the work item</param>
  625. /// <returns>Returns a work item result</returns>
  626. public IWorkItemResult QueueWorkItem(WorkItemCallback callback, WorkItemPriority workItemPriority)
  627. {
  628. ValidateNotDisposed();
  629. ValidateCallback(callback);
  630. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, workItemPriority);
  631. Enqueue(workItem);
  632. return workItem.GetWorkItemResult();
  633. }
  634. /// <summary>
  635. /// Queue a work item
  636. /// </summary>
  637. /// <param name="workItemInfo">Work item info</param>
  638. /// <param name="callback">A callback to execute</param>
  639. /// <returns>Returns a work item result</returns>
  640. public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback)
  641. {
  642. ValidateNotDisposed();
  643. ValidateCallback(callback);
  644. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, workItemInfo, callback);
  645. Enqueue(workItem);
  646. return workItem.GetWorkItemResult();
  647. }
  648. /// <summary>
  649. /// Queue a work item
  650. /// </summary>
  651. /// <param name="callback">A callback to execute</param>
  652. /// <param name="state">
  653. /// The context object of the work item. Used for passing arguments to the work item.
  654. /// </param>
  655. /// <returns>Returns a work item result</returns>
  656. public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state)
  657. {
  658. ValidateNotDisposed();
  659. ValidateCallback(callback);
  660. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state);
  661. Enqueue(workItem);
  662. return workItem.GetWorkItemResult();
  663. }
  664. /// <summary>
  665. /// Queue a work item
  666. /// </summary>
  667. /// <param name="callback">A callback to execute</param>
  668. /// <param name="state">
  669. /// The context object of the work item. Used for passing arguments to the work item.
  670. /// </param>
  671. /// <param name="workItemPriority">The work item priority</param>
  672. /// <returns>Returns a work item result</returns>
  673. public IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, WorkItemPriority workItemPriority)
  674. {
  675. ValidateNotDisposed();
  676. ValidateCallback(callback);
  677. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, workItemPriority);
  678. Enqueue(workItem);
  679. return workItem.GetWorkItemResult();
  680. }
  681. /// <summary>
  682. /// Queue a work item
  683. /// </summary>
  684. /// <param name="workItemInfo">Work item information</param>
  685. /// <param name="callback">A callback to execute</param>
  686. /// <param name="state">
  687. /// The context object of the work item. Used for passing arguments to the work item.
  688. /// </param>
  689. /// <returns>Returns a work item result</returns>
  690. public IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state)
  691. {
  692. ValidateNotDisposed();
  693. ValidateCallback(callback);
  694. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, workItemInfo, callback, state);
  695. Enqueue(workItem);
  696. return workItem.GetWorkItemResult();
  697. }
  698. /// <summary>
  699. /// Queue a work item
  700. /// </summary>
  701. /// <param name="callback">A callback to execute</param>
  702. /// <param name="state">
  703. /// The context object of the work item. Used for passing arguments to the work item.
  704. /// </param>
  705. /// <param name="postExecuteWorkItemCallback">
  706. /// A delegate to call after the callback completion
  707. /// </param>
  708. /// <returns>Returns a work item result</returns>
  709. public IWorkItemResult QueueWorkItem(
  710. WorkItemCallback callback,
  711. object state,
  712. PostExecuteWorkItemCallback postExecuteWorkItemCallback)
  713. {
  714. ValidateNotDisposed();
  715. ValidateCallback(callback);
  716. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, postExecuteWorkItemCallback);
  717. Enqueue(workItem);
  718. return workItem.GetWorkItemResult();
  719. }
  720. /// <summary>
  721. /// Queue a work item
  722. /// </summary>
  723. /// <param name="callback">A callback to execute</param>
  724. /// <param name="state">
  725. /// The context object of the work item. Used for passing arguments to the work item.
  726. /// </param>
  727. /// <param name="postExecuteWorkItemCallback">
  728. /// A delegate to call after the callback completion
  729. /// </param>
  730. /// <param name="workItemPriority">The work item priority</param>
  731. /// <returns>Returns a work item result</returns>
  732. public IWorkItemResult QueueWorkItem(
  733. WorkItemCallback callback,
  734. object state,
  735. PostExecuteWorkItemCallback postExecuteWorkItemCallback,
  736. WorkItemPriority workItemPriority)
  737. {
  738. ValidateNotDisposed();
  739. ValidateCallback(callback);
  740. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, postExecuteWorkItemCallback, workItemPriority);
  741. Enqueue(workItem);
  742. return workItem.GetWorkItemResult();
  743. }
  744. /// <summary>
  745. /// Queue a work item
  746. /// </summary>
  747. /// <param name="callback">A callback to execute</param>
  748. /// <param name="state">
  749. /// The context object of the work item. Used for passing arguments to the work item.
  750. /// </param>
  751. /// <param name="postExecuteWorkItemCallback">
  752. /// A delegate to call after the callback completion
  753. /// </param>
  754. /// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
  755. /// <returns>Returns a work item result</returns>
  756. public IWorkItemResult QueueWorkItem(
  757. WorkItemCallback callback,
  758. object state,
  759. PostExecuteWorkItemCallback postExecuteWorkItemCallback,
  760. CallToPostExecute callToPostExecute)
  761. {
  762. ValidateNotDisposed();
  763. ValidateCallback(callback);
  764. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute);
  765. Enqueue(workItem);
  766. return workItem.GetWorkItemResult();
  767. }
  768. /// <summary>
  769. /// Queue a work item
  770. /// </summary>
  771. /// <param name="callback">A callback to execute</param>
  772. /// <param name="state">
  773. /// The context object of the work item. Used for passing arguments to the work item.
  774. /// </param>
  775. /// <param name="postExecuteWorkItemCallback">
  776. /// A delegate to call after the callback completion
  777. /// </param>
  778. /// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param>
  779. /// <param name="workItemPriority">The work item priority</param>
  780. /// <returns>Returns a work item result</returns>
  781. public IWorkItemResult QueueWorkItem(
  782. WorkItemCallback callback,
  783. object state,
  784. PostExecuteWorkItemCallback postExecuteWorkItemCallback,
  785. CallToPostExecute callToPostExecute,
  786. WorkItemPriority workItemPriority)
  787. {
  788. ValidateNotDisposed();
  789. ValidateCallback(callback);
  790. WorkItem workItem = WorkItemFactory.CreateWorkItem(this, _stpStartInfo, callback, state, postExecuteWorkItemCallback, callToPostExecute, workItemPriority);
  791. Enqueue(workItem);
  792. return workItem.GetWorkItemResult();
  793. }
  794. /// <summary>
  795. /// Wait for the thread pool to be idle
  796. /// </summary>
  797. public void WaitForIdle()
  798. {
  799. WaitForIdle(Timeout.Infinite);
  800. }
  801. /// <summary>
  802. /// Wait for the thread pool to be idle
  803. /// </summary>
  804. public bool WaitForIdle(TimeSpan timeout)
  805. {
  806. return WaitForIdle((int)timeout.TotalMilliseconds);
  807. }
  808. /// <summary>
  809. /// Wait for the thread pool to be idle
  810. /// </summary>
  811. public bool WaitForIdle(int millisecondsTimeout)
  812. {
  813. ValidateWaitForIdle();
  814. return _isIdleWaitHandle.WaitOne(millisecondsTimeout, false);
  815. }
  816. private void ValidateWaitForIdle()
  817. {
  818. if(_smartThreadPool == this)
  819. {
  820. throw new NotSupportedException(
  821. "WaitForIdle cannot be called from a thread on its SmartThreadPool, it will cause may cause a deadlock");
  822. }
  823. }
  824. internal void ValidateWorkItemsGroupWaitForIdle(IWorkItemsGroup workItemsGroup)
  825. {
  826. ValidateWorkItemsGroupWaitForIdleImpl(workItemsGroup, SmartThreadPool._currentWorkItem);
  827. if ((null != workItemsGroup) &&
  828. (null != SmartThreadPool._currentWorkItem) &&
  829. SmartThreadPool._currentWorkItem.WasQueuedBy(workItemsGroup))
  830. {
  831. throw new NotSupportedException("WaitForIdle cannot be called from a thread on its SmartThreadPool, it will cause may cause a deadlock");
  832. }
  833. }
  834. [MethodImpl(MethodImplOptions.NoInlining)]
  835. private void ValidateWorkItemsGroupWaitForIdleImpl(IWorkItemsGroup workItemsGroup, WorkItem workItem)
  836. {
  837. if ((null != workItemsGroup) &&
  838. (null != workItem) &&
  839. workItem.WasQueuedBy(workItemsGroup))
  840. {
  841. throw new NotSupportedException("WaitForIdle cannot be called from a thread on its SmartThreadPool, it will cause may cause a deadlock");
  842. }
  843. }
  844. /// <summary>
  845. /// Force the SmartThreadPool to shutdown
  846. /// </summary>
  847. public void Shutdown()
  848. {
  849. Shutdown(true, 0);
  850. }
  851. public void Shutdown(bool forceAbort, TimeSpan timeout)
  852. {
  853. Shutdown(forceAbort, (int)timeout.TotalMilliseconds);
  854. }
  855. /// <summary>
  856. /// Empties the queue of work items and abort the threads in the pool.
  857. /// </summary>
  858. public void Shutdown(bool forceAbort, int millisecondsTimeout)
  859. {
  860. ValidateNotDisposed();
  861. ISTPInstancePerformanceCounters pcs = _pcs;
  862. if (NullSTPInstancePerformanceCounters.Instance != _pcs)
  863. {
  864. _pcs.Dispose();
  865. // Set the _pcs to "null" to stop updating the performance
  866. // counters
  867. _pcs = NullSTPInstancePerformanceCounters.Instance;
  868. }
  869. Thread [] threads = null;
  870. lock(_workerThreads.SyncRoot)
  871. {
  872. // Shutdown the work items queue
  873. _workItemsQueue.Dispose();
  874. // Signal the threads to exit
  875. _shutdown = true;
  876. _shuttingDownEvent.Set();
  877. // Make a copy of the threads' references in the pool
  878. threads = new Thread [_workerThreads.Count];
  879. _workerThreads.Keys.CopyTo(threads, 0);
  880. }
  881. int millisecondsLeft = millisecondsTimeout;
  882. DateTime start = DateTime.Now;
  883. bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout);
  884. bool timeout = false;
  885. // Each iteration we update the time left for the timeout.
  886. foreach(Thread thread in threads)
  887. {
  888. // Join don't work with negative numbers
  889. if (!waitInfinitely && (millisecondsLeft < 0))
  890. {
  891. timeout = true;
  892. break;
  893. }
  894. // Wait for the thread to terminate
  895. bool success = thread.Join(millisecondsLeft);
  896. if(!success)
  897. {
  898. timeout = true;
  899. break;
  900. }
  901. if(!waitInfinitely)
  902. {
  903. // Update the time left to wait
  904. TimeSpan ts = DateTime.Now - start;
  905. millisecondsLeft = millisecondsTimeout - (int)ts.TotalMilliseconds;
  906. }
  907. }
  908. if (timeout && forceAbort)
  909. {
  910. // Abort the threads in the pool
  911. foreach(Thread thread in threads)
  912. {
  913. if ((thread != null) && thread.IsAlive)
  914. {
  915. try
  916. {
  917. thread.Abort("Shutdown");
  918. }
  919. catch(SecurityException e)
  920. {
  921. e.GetHashCode();
  922. }
  923. catch(ThreadStateException ex)
  924. {
  925. ex.GetHashCode();
  926. // In case the thread has been terminated
  927. // after the check if it is alive.
  928. }
  929. }
  930. }
  931. }
  932. // Dispose of the performance counters
  933. pcs.Dispose();
  934. }
  935. /// <summary>
  936. /// Wait for all work items to complete
  937. /// </summary>
  938. /// <param name="workItemResults">Array of work item result objects</param>
  939. /// <returns>
  940. /// true when every work item in workItemResults has completed; otherwise false.
  941. /// </returns>
  942. public static bool WaitAll(
  943. IWorkItemResult [] workItemResults)
  944. {
  945. return WaitAll(workItemResults, Timeout.Infinite, true);
  946. }
  947. /// <summary>
  948. /// Wait for all work items to complete
  949. /// </summary>
  950. /// <param name="workItemResults">Array of work item result objects</param>
  951. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  952. /// <param name="exitContext">
  953. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  954. /// </param>
  955. /// <returns>
  956. /// true when every work item in workItemResults has completed; otherwise false.
  957. /// </returns>
  958. public static bool WaitAll(
  959. IWorkItemResult [] workItemResults,
  960. TimeSpan timeout,
  961. bool exitContext)
  962. {
  963. return WaitAll(workItemResults, (int)timeout.TotalMilliseconds, exitContext);
  964. }
  965. /// <summary>
  966. /// Wait for all work items to complete
  967. /// </summary>
  968. /// <param name="workItemResults">Array of work item result objects</param>
  969. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  970. /// <param name="exitContext">
  971. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  972. /// </param>
  973. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  974. /// <returns>
  975. /// true when every work item in workItemResults has completed; otherwise false.
  976. /// </returns>
  977. public static bool WaitAll(
  978. IWorkItemResult [] workItemResults,
  979. TimeSpan timeout,
  980. bool exitContext,
  981. WaitHandle cancelWaitHandle)
  982. {
  983. return WaitAll(workItemResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  984. }
  985. /// <summary>
  986. /// Wait for all work items to complete
  987. /// </summary>
  988. /// <param name="workItemResults">Array of work item result objects</param>
  989. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  990. /// <param name="exitContext">
  991. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  992. /// </param>
  993. /// <returns>
  994. /// true when every work item in workItemResults has completed; otherwise false.
  995. /// </returns>
  996. public static bool WaitAll(
  997. IWorkItemResult [] workItemResults,
  998. int millisecondsTimeout,
  999. bool exitContext)
  1000. {
  1001. return WorkItem.WaitAll(workItemResults, millisecondsTimeout, exitContext, null);
  1002. }
  1003. /// <summary>
  1004. /// Wait for all work items to complete
  1005. /// </summary>
  1006. /// <param name="workItemResults">Array of work item result objects</param>
  1007. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  1008. /// <param name="exitContext">
  1009. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1010. /// </param>
  1011. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  1012. /// <returns>
  1013. /// true when every work item in workItemResults has completed; otherwise false.
  1014. /// </returns>
  1015. public static bool WaitAll(
  1016. IWorkItemResult [] workItemResults,
  1017. int millisecondsTimeout,
  1018. bool exitContext,
  1019. WaitHandle cancelWaitHandle)
  1020. {
  1021. return WorkItem.WaitAll(workItemResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  1022. }
  1023. /// <summary>
  1024. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1025. /// </summary>
  1026. /// <param name="workItemResults">Array of work item result objects</param>
  1027. /// <returns>
  1028. /// The array index of the work item result that satisfied the wait, or WaitTimeout if any of the work items has been canceled.
  1029. /// </returns>
  1030. public static int WaitAny(
  1031. IWorkItemResult [] workItemResults)
  1032. {
  1033. return WaitAny(workItemResults, Timeout.Infinite, true);
  1034. }
  1035. /// <summary>
  1036. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1037. /// </summary>
  1038. /// <param name="workItemResults">Array of work item result objects</param>
  1039. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  1040. /// <param name="exitContext">
  1041. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1042. /// </param>
  1043. /// <returns>
  1044. /// 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.
  1045. /// </returns>
  1046. public static int WaitAny(
  1047. IWorkItemResult [] workItemResults,
  1048. TimeSpan timeout,
  1049. bool exitContext)
  1050. {
  1051. return WaitAny(workItemResults, (int)timeout.TotalMilliseconds, exitContext);
  1052. }
  1053. /// <summary>
  1054. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1055. /// </summary>
  1056. /// <param name="workItemResults">Array of work item result objects</param>
  1057. /// <param name="timeout">The number of milliseconds to wait, or a TimeSpan that represents -1 milliseconds to wait indefinitely. </param>
  1058. /// <param name="exitContext">
  1059. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1060. /// </param>
  1061. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  1062. /// <returns>
  1063. /// 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.
  1064. /// </returns>
  1065. public static int WaitAny(
  1066. IWorkItemResult [] workItemResults,
  1067. TimeSpan timeout,
  1068. bool exitContext,
  1069. WaitHandle cancelWaitHandle)
  1070. {
  1071. return WaitAny(workItemResults, (int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle);
  1072. }
  1073. /// <summary>
  1074. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1075. /// </summary>
  1076. /// <param name="workItemResults">Array of work item result objects</param>
  1077. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  1078. /// <param name="exitContext">
  1079. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1080. /// </param>
  1081. /// <returns>
  1082. /// 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.
  1083. /// </returns>
  1084. public static int WaitAny(
  1085. IWorkItemResult [] workItemResults,
  1086. int millisecondsTimeout,
  1087. bool exitContext)
  1088. {
  1089. return WorkItem.WaitAny(workItemResults, millisecondsTimeout, exitContext, null);
  1090. }
  1091. /// <summary>
  1092. /// Waits for any of the work items in the specified array to complete, cancel, or timeout
  1093. /// </summary>
  1094. /// <param name="workItemResults">Array of work item result objects</param>
  1095. /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param>
  1096. /// <param name="exitContext">
  1097. /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
  1098. /// </param>
  1099. /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param>
  1100. /// <returns>
  1101. /// 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.
  1102. /// </returns>
  1103. public static int WaitAny(
  1104. IWorkItemResult [] workItemResults,
  1105. int millisecondsTimeout,
  1106. bool exitContext,
  1107. WaitHandle cancelWaitHandle)
  1108. {
  1109. return WorkItem.WaitAny(workItemResults, millisecondsTimeout, exitContext, cancelWaitHandle);
  1110. }
  1111. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency)
  1112. {
  1113. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, _stpStartInfo);
  1114. return workItemsGroup;
  1115. }
  1116. public IWorkItemsGroup CreateWorkItemsGroup(int concurrency, WIGStartInfo wigStartInfo)
  1117. {
  1118. IWorkItemsGroup workItemsGroup = new WorkItemsGroup(this, concurrency, wigStartInfo);
  1119. return workItemsGroup;
  1120. }
  1121. public event WorkItemsGroupIdleHandler OnIdle
  1122. {
  1123. add
  1124. {
  1125. throw new NotImplementedException("This event is not implemented in the SmartThreadPool class. Please create a WorkItemsGroup in order to use this feature.");
  1126. //_onIdle += value;
  1127. }
  1128. remove
  1129. {
  1130. throw new NotImplementedException("This event is not implemented in the SmartThreadPool class. Please create a WorkItemsGroup in order to use this feature.");
  1131. //_onIdle -= value;
  1132. }
  1133. }
  1134. public void Cancel()
  1135. {
  1136. ICollection workItemsGroups = _workItemsGroups.Values;
  1137. foreach(WorkItemsGroup workItemsGroup in workItemsGroups)
  1138. {
  1139. workItemsGroup.Cancel();
  1140. }
  1141. }
  1142. public void Start()
  1143. {
  1144. lock (this)
  1145. {
  1146. if (!this._stpStartInfo.StartSuspended)
  1147. {
  1148. return;
  1149. }
  1150. _stpStartInfo.StartSuspended = false;
  1151. }
  1152. ICollection workItemsGroups = _workItemsGroups.Values;
  1153. foreach(WorkItemsGroup workItemsGroup in workItemsGroups)
  1154. {
  1155. workItemsGroup.OnSTPIsStarting();
  1156. }
  1157. StartOptimalNumberOfThreads();
  1158. }
  1159. #endregion
  1160. #region Properties
  1161. /// <summary>
  1162. /// Get/Set the name of the SmartThreadPool instance
  1163. /// </summary>
  1164. public string Name
  1165. {
  1166. get
  1167. {
  1168. return _name;
  1169. }
  1170. set
  1171. {
  1172. _name = value;
  1173. }
  1174. }
  1175. /// <summary>
  1176. /// Get the lower limit of threads in the pool.
  1177. /// </summary>
  1178. public int MinThreads
  1179. {
  1180. get
  1181. {
  1182. ValidateNotDisposed();
  1183. return _stpStartInfo.MinWorkerThreads;
  1184. }
  1185. }
  1186. /// <summary>
  1187. /// Get the upper limit of threads in the pool.
  1188. /// </summary>
  1189. public int MaxThreads
  1190. {
  1191. get
  1192. {
  1193. ValidateNotDisposed();
  1194. return _stpStartInfo.MaxWorkerThreads;
  1195. }
  1196. }
  1197. /// <summary>
  1198. /// Get the number of threads in the thread pool.
  1199. /// Should be between the lower and the upper limits.
  1200. /// </summary>
  1201. public int ActiveThreads
  1202. {
  1203. get
  1204. {
  1205. ValidateNotDisposed();
  1206. return _workerThreads.Count;
  1207. }
  1208. }
  1209. /// <summary>
  1210. /// Get the number of busy (not idle) threads in the thread pool.
  1211. /// </summary>
  1212. public int InUseThreads
  1213. {
  1214. get
  1215. {
  1216. ValidateNotDisposed();
  1217. return _inUseWorkerThreads;
  1218. }
  1219. }
  1220. /// <summary>
  1221. /// Get the number of work items in the queue.
  1222. /// </summary>
  1223. public int WaitingCallbacks
  1224. {
  1225. get
  1226. {
  1227. ValidateNotDisposed();
  1228. return _workItemsQueue.Count;
  1229. }
  1230. }
  1231. public event EventHandler Idle
  1232. {
  1233. add
  1234. {
  1235. _stpIdle += value;
  1236. }
  1237. remove
  1238. {
  1239. _stpIdle -= value;
  1240. }
  1241. }
  1242. #endregion
  1243. #region IDisposable Members
  1244. // ~SmartThreadPool()
  1245. // {
  1246. // Dispose();
  1247. // }
  1248. public void Dispose()
  1249. {
  1250. if (!_isDisposed)
  1251. {
  1252. if (!_shutdown)
  1253. {
  1254. Shutdown();
  1255. }
  1256. if (null != _shuttingDownEvent)
  1257. {
  1258. _shuttingDownEvent.Close();
  1259. _shuttingDownEvent = null;
  1260. }
  1261. _workerThreads.Clear();
  1262. _isDisposed = true;
  1263. GC.SuppressFinalize(this);
  1264. }
  1265. }
  1266. private void ValidateNotDisposed()
  1267. {
  1268. if(_isDisposed)
  1269. {
  1270. throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown");
  1271. }
  1272. }
  1273. #endregion
  1274. }
  1275. #endregion
  1276. }