SmartThreadPool.cs 54 KB

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