ThreadPool.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. /*=============================================================================
  5. **
  6. **
  7. **
  8. ** Purpose: Class for creating and managing a threadpool
  9. **
  10. **
  11. =============================================================================*/
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.Diagnostics;
  15. using System.Diagnostics.CodeAnalysis;
  16. using System.Diagnostics.Tracing;
  17. using System.Runtime.CompilerServices;
  18. using System.Runtime.InteropServices;
  19. using System.Threading.Tasks;
  20. using Internal.Runtime.CompilerServices;
  21. namespace System.Threading
  22. {
  23. internal static class ThreadPoolGlobals
  24. {
  25. public static volatile bool threadPoolInitialized;
  26. public static bool enableWorkerTracking;
  27. public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
  28. /// <summary>Shim used to invoke <see cref="IAsyncStateMachineBox.MoveNext"/> of the supplied <see cref="IAsyncStateMachineBox"/>.</summary>
  29. internal static readonly Action<object?> s_invokeAsyncStateMachineBox = state =>
  30. {
  31. if (!(state is IAsyncStateMachineBox box))
  32. {
  33. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state);
  34. return;
  35. }
  36. box.MoveNext();
  37. };
  38. }
  39. [StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing
  40. internal sealed class ThreadPoolWorkQueue
  41. {
  42. internal static class WorkStealingQueueList
  43. {
  44. #pragma warning disable CA1825 // avoid the extra generic instantation for Array.Empty<T>(); this is the only place we'll ever create this array
  45. private static volatile WorkStealingQueue[] _queues = new WorkStealingQueue[0];
  46. #pragma warning restore CA1825
  47. public static WorkStealingQueue[] Queues => _queues;
  48. public static void Add(WorkStealingQueue queue)
  49. {
  50. Debug.Assert(queue != null);
  51. while (true)
  52. {
  53. WorkStealingQueue[] oldQueues = _queues;
  54. Debug.Assert(Array.IndexOf(oldQueues, queue) == -1);
  55. var newQueues = new WorkStealingQueue[oldQueues.Length + 1];
  56. Array.Copy(oldQueues, newQueues, oldQueues.Length);
  57. newQueues[^1] = queue;
  58. if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
  59. {
  60. break;
  61. }
  62. }
  63. }
  64. public static void Remove(WorkStealingQueue queue)
  65. {
  66. Debug.Assert(queue != null);
  67. while (true)
  68. {
  69. WorkStealingQueue[] oldQueues = _queues;
  70. if (oldQueues.Length == 0)
  71. {
  72. return;
  73. }
  74. int pos = Array.IndexOf(oldQueues, queue);
  75. if (pos == -1)
  76. {
  77. Debug.Fail("Should have found the queue");
  78. return;
  79. }
  80. var newQueues = new WorkStealingQueue[oldQueues.Length - 1];
  81. if (pos == 0)
  82. {
  83. Array.Copy(oldQueues, 1, newQueues, 0, newQueues.Length);
  84. }
  85. else if (pos == oldQueues.Length - 1)
  86. {
  87. Array.Copy(oldQueues, newQueues, newQueues.Length);
  88. }
  89. else
  90. {
  91. Array.Copy(oldQueues, newQueues, pos);
  92. Array.Copy(oldQueues, pos + 1, newQueues, pos, newQueues.Length - pos);
  93. }
  94. if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues)
  95. {
  96. break;
  97. }
  98. }
  99. }
  100. }
  101. internal sealed class WorkStealingQueue
  102. {
  103. private const int INITIAL_SIZE = 32;
  104. internal volatile object?[] m_array = new object[INITIAL_SIZE]; // SOS's ThreadPool command depends on this name
  105. private volatile int m_mask = INITIAL_SIZE - 1;
  106. #if DEBUG
  107. // in debug builds, start at the end so we exercise the index reset logic.
  108. private const int START_INDEX = int.MaxValue;
  109. #else
  110. private const int START_INDEX = 0;
  111. #endif
  112. private volatile int m_headIndex = START_INDEX;
  113. private volatile int m_tailIndex = START_INDEX;
  114. private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false);
  115. public void LocalPush(object obj)
  116. {
  117. int tail = m_tailIndex;
  118. // We're going to increment the tail; if we'll overflow, then we need to reset our counts
  119. if (tail == int.MaxValue)
  120. {
  121. bool lockTaken = false;
  122. try
  123. {
  124. m_foreignLock.Enter(ref lockTaken);
  125. if (m_tailIndex == int.MaxValue)
  126. {
  127. //
  128. // Rather than resetting to zero, we'll just mask off the bits we don't care about.
  129. // This way we don't need to rearrange the items already in the queue; they'll be found
  130. // correctly exactly where they are. One subtlety here is that we need to make sure that
  131. // if head is currently < tail, it remains that way. This happens to just fall out from
  132. // the bit-masking, because we only do this if tail == int.MaxValue, meaning that all
  133. // bits are set, so all of the bits we're keeping will also be set. Thus it's impossible
  134. // for the head to end up > than the tail, since you can't set any more bits than all of
  135. // them.
  136. //
  137. m_headIndex &= m_mask;
  138. m_tailIndex = tail = m_tailIndex & m_mask;
  139. Debug.Assert(m_headIndex <= m_tailIndex);
  140. }
  141. }
  142. finally
  143. {
  144. if (lockTaken)
  145. m_foreignLock.Exit(useMemoryBarrier: true);
  146. }
  147. }
  148. // When there are at least 2 elements' worth of space, we can take the fast path.
  149. if (tail < m_headIndex + m_mask)
  150. {
  151. Volatile.Write(ref m_array[tail & m_mask], obj);
  152. m_tailIndex = tail + 1;
  153. }
  154. else
  155. {
  156. // We need to contend with foreign pops, so we lock.
  157. bool lockTaken = false;
  158. try
  159. {
  160. m_foreignLock.Enter(ref lockTaken);
  161. int head = m_headIndex;
  162. int count = m_tailIndex - m_headIndex;
  163. // If there is still space (one left), just add the element.
  164. if (count >= m_mask)
  165. {
  166. // We're full; expand the queue by doubling its size.
  167. var newArray = new object?[m_array.Length << 1];
  168. for (int i = 0; i < m_array.Length; i++)
  169. newArray[i] = m_array[(i + head) & m_mask];
  170. // Reset the field values, incl. the mask.
  171. m_array = newArray;
  172. m_headIndex = 0;
  173. m_tailIndex = tail = count;
  174. m_mask = (m_mask << 1) | 1;
  175. }
  176. Volatile.Write(ref m_array[tail & m_mask], obj);
  177. m_tailIndex = tail + 1;
  178. }
  179. finally
  180. {
  181. if (lockTaken)
  182. m_foreignLock.Exit(useMemoryBarrier: false);
  183. }
  184. }
  185. }
  186. public bool LocalFindAndPop(object obj)
  187. {
  188. // Fast path: check the tail. If equal, we can skip the lock.
  189. if (m_array[(m_tailIndex - 1) & m_mask] == obj)
  190. {
  191. object? unused = LocalPop();
  192. Debug.Assert(unused == null || unused == obj);
  193. return unused != null;
  194. }
  195. // Else, do an O(N) search for the work item. The theory of work stealing and our
  196. // inlining logic is that most waits will happen on recently queued work. And
  197. // since recently queued work will be close to the tail end (which is where we
  198. // begin our search), we will likely find it quickly. In the worst case, we
  199. // will traverse the whole local queue; this is typically not going to be a
  200. // problem (although degenerate cases are clearly an issue) because local work
  201. // queues tend to be somewhat shallow in length, and because if we fail to find
  202. // the work item, we are about to block anyway (which is very expensive).
  203. for (int i = m_tailIndex - 2; i >= m_headIndex; i--)
  204. {
  205. if (m_array[i & m_mask] == obj)
  206. {
  207. // If we found the element, block out steals to avoid interference.
  208. bool lockTaken = false;
  209. try
  210. {
  211. m_foreignLock.Enter(ref lockTaken);
  212. // If we encountered a race condition, bail.
  213. if (m_array[i & m_mask] == null)
  214. return false;
  215. // Otherwise, null out the element.
  216. Volatile.Write(ref m_array[i & m_mask], null);
  217. // And then check to see if we can fix up the indexes (if we're at
  218. // the edge). If we can't, we just leave nulls in the array and they'll
  219. // get filtered out eventually (but may lead to superfluous resizing).
  220. if (i == m_tailIndex)
  221. m_tailIndex--;
  222. else if (i == m_headIndex)
  223. m_headIndex++;
  224. return true;
  225. }
  226. finally
  227. {
  228. if (lockTaken)
  229. m_foreignLock.Exit(useMemoryBarrier: false);
  230. }
  231. }
  232. }
  233. return false;
  234. }
  235. public object? LocalPop() => m_headIndex < m_tailIndex ? LocalPopCore() : null;
  236. private object? LocalPopCore()
  237. {
  238. while (true)
  239. {
  240. int tail = m_tailIndex;
  241. if (m_headIndex >= tail)
  242. {
  243. return null;
  244. }
  245. // Decrement the tail using a fence to ensure subsequent read doesn't come before.
  246. tail--;
  247. Interlocked.Exchange(ref m_tailIndex, tail);
  248. // If there is no interaction with a take, we can head down the fast path.
  249. if (m_headIndex <= tail)
  250. {
  251. int idx = tail & m_mask;
  252. object? obj = Volatile.Read(ref m_array[idx]);
  253. // Check for nulls in the array.
  254. if (obj == null) continue;
  255. m_array[idx] = null;
  256. return obj;
  257. }
  258. else
  259. {
  260. // Interaction with takes: 0 or 1 elements left.
  261. bool lockTaken = false;
  262. try
  263. {
  264. m_foreignLock.Enter(ref lockTaken);
  265. if (m_headIndex <= tail)
  266. {
  267. // Element still available. Take it.
  268. int idx = tail & m_mask;
  269. object? obj = Volatile.Read(ref m_array[idx]);
  270. // Check for nulls in the array.
  271. if (obj == null) continue;
  272. m_array[idx] = null;
  273. return obj;
  274. }
  275. else
  276. {
  277. // If we encountered a race condition and element was stolen, restore the tail.
  278. m_tailIndex = tail + 1;
  279. return null;
  280. }
  281. }
  282. finally
  283. {
  284. if (lockTaken)
  285. m_foreignLock.Exit(useMemoryBarrier: false);
  286. }
  287. }
  288. }
  289. }
  290. public bool CanSteal => m_headIndex < m_tailIndex;
  291. public object? TrySteal(ref bool missedSteal)
  292. {
  293. while (true)
  294. {
  295. if (CanSteal)
  296. {
  297. bool taken = false;
  298. try
  299. {
  300. m_foreignLock.TryEnter(ref taken);
  301. if (taken)
  302. {
  303. // Increment head, and ensure read of tail doesn't move before it (fence).
  304. int head = m_headIndex;
  305. Interlocked.Exchange(ref m_headIndex, head + 1);
  306. if (head < m_tailIndex)
  307. {
  308. int idx = head & m_mask;
  309. object? obj = Volatile.Read(ref m_array[idx]);
  310. // Check for nulls in the array.
  311. if (obj == null) continue;
  312. m_array[idx] = null;
  313. return obj;
  314. }
  315. else
  316. {
  317. // Failed, restore head.
  318. m_headIndex = head;
  319. }
  320. }
  321. }
  322. finally
  323. {
  324. if (taken)
  325. m_foreignLock.Exit(useMemoryBarrier: false);
  326. }
  327. missedSteal = true;
  328. }
  329. return null;
  330. }
  331. }
  332. public int Count
  333. {
  334. get
  335. {
  336. bool lockTaken = false;
  337. try
  338. {
  339. m_foreignLock.Enter(ref lockTaken);
  340. return Math.Max(0, m_tailIndex - m_headIndex);
  341. }
  342. finally
  343. {
  344. if (lockTaken)
  345. {
  346. m_foreignLock.Exit(useMemoryBarrier: false);
  347. }
  348. }
  349. }
  350. }
  351. }
  352. internal bool loggingEnabled;
  353. internal readonly ConcurrentQueue<object> workItems = new ConcurrentQueue<object>(); // SOS's ThreadPool command depends on this name
  354. private readonly Internal.PaddingFor32 pad1;
  355. private volatile int numOutstandingThreadRequests = 0;
  356. private readonly Internal.PaddingFor32 pad2;
  357. public ThreadPoolWorkQueue()
  358. {
  359. loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
  360. }
  361. public ThreadPoolWorkQueueThreadLocals GetOrCreateThreadLocals() =>
  362. ThreadPoolWorkQueueThreadLocals.threadLocals ?? CreateThreadLocals();
  363. [MethodImpl(MethodImplOptions.NoInlining)]
  364. private ThreadPoolWorkQueueThreadLocals CreateThreadLocals()
  365. {
  366. Debug.Assert(ThreadPoolWorkQueueThreadLocals.threadLocals == null);
  367. return ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this);
  368. }
  369. internal void EnsureThreadRequested()
  370. {
  371. //
  372. // If we have not yet requested #procs threads, then request a new thread.
  373. //
  374. // CoreCLR: Note that there is a separate count in the VM which has already been incremented
  375. // by the VM by the time we reach this point.
  376. //
  377. int count = numOutstandingThreadRequests;
  378. while (count < Environment.ProcessorCount)
  379. {
  380. int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count);
  381. if (prev == count)
  382. {
  383. ThreadPool.RequestWorkerThread();
  384. break;
  385. }
  386. count = prev;
  387. }
  388. }
  389. internal void MarkThreadRequestSatisfied()
  390. {
  391. //
  392. // One of our outstanding thread requests has been satisfied.
  393. // Decrement the count so that future calls to EnsureThreadRequested will succeed.
  394. //
  395. // CoreCLR: Note that there is a separate count in the VM which has already been decremented
  396. // by the VM by the time we reach this point.
  397. //
  398. int count = numOutstandingThreadRequests;
  399. while (count > 0)
  400. {
  401. int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count - 1, count);
  402. if (prev == count)
  403. {
  404. break;
  405. }
  406. count = prev;
  407. }
  408. }
  409. public void Enqueue(object callback, bool forceGlobal)
  410. {
  411. Debug.Assert((callback is IThreadPoolWorkItem) ^ (callback is Task));
  412. if (loggingEnabled)
  413. System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(callback);
  414. ThreadPoolWorkQueueThreadLocals? tl = null;
  415. if (!forceGlobal)
  416. tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
  417. if (null != tl)
  418. {
  419. tl.workStealingQueue.LocalPush(callback);
  420. }
  421. else
  422. {
  423. workItems.Enqueue(callback);
  424. }
  425. EnsureThreadRequested();
  426. }
  427. internal bool LocalFindAndPop(object callback)
  428. {
  429. ThreadPoolWorkQueueThreadLocals? tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
  430. return tl != null && tl.workStealingQueue.LocalFindAndPop(callback);
  431. }
  432. public object? Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal)
  433. {
  434. WorkStealingQueue localWsq = tl.workStealingQueue;
  435. object? callback;
  436. if ((callback = localWsq.LocalPop()) == null && // first try the local queue
  437. !workItems.TryDequeue(out callback)) // then try the global queue
  438. {
  439. // finally try to steal from another thread's local queue
  440. WorkStealingQueue[] queues = WorkStealingQueueList.Queues;
  441. int c = queues.Length;
  442. Debug.Assert(c > 0, "There must at least be a queue for this thread.");
  443. int maxIndex = c - 1;
  444. int i = tl.random.Next(c);
  445. while (c > 0)
  446. {
  447. i = (i < maxIndex) ? i + 1 : 0;
  448. WorkStealingQueue otherQueue = queues[i];
  449. if (otherQueue != localWsq && otherQueue.CanSteal)
  450. {
  451. callback = otherQueue.TrySteal(ref missedSteal);
  452. if (callback != null)
  453. {
  454. break;
  455. }
  456. }
  457. c--;
  458. }
  459. }
  460. return callback;
  461. }
  462. public long LocalCount
  463. {
  464. get
  465. {
  466. long count = 0;
  467. foreach (WorkStealingQueue workStealingQueue in WorkStealingQueueList.Queues)
  468. {
  469. count += workStealingQueue.Count;
  470. }
  471. return count;
  472. }
  473. }
  474. public long GlobalCount => workItems.Count;
  475. /// <summary>
  476. /// Dispatches work items to this thread.
  477. /// </summary>
  478. /// <returns>
  479. /// <c>true</c> if this thread did as much work as was available or its quantum expired.
  480. /// <c>false</c> if this thread stopped working early.
  481. /// </returns>
  482. internal static bool Dispatch()
  483. {
  484. ThreadPoolWorkQueue outerWorkQueue = ThreadPoolGlobals.workQueue;
  485. //
  486. // Save the start time
  487. //
  488. int startTickCount = Environment.TickCount;
  489. //
  490. // Update our records to indicate that an outstanding request for a thread has now been fulfilled.
  491. // From this point on, we are responsible for requesting another thread if we stop working for any
  492. // reason, and we believe there might still be work in the queue.
  493. //
  494. // CoreCLR: Note that if this thread is aborted before we get a chance to request another one, the VM will
  495. // record a thread request on our behalf. So we don't need to worry about getting aborted right here.
  496. //
  497. outerWorkQueue.MarkThreadRequestSatisfied();
  498. // Has the desire for logging changed since the last time we entered?
  499. outerWorkQueue.loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
  500. //
  501. // Assume that we're going to need another thread if this one returns to the VM. We'll set this to
  502. // false later, but only if we're absolutely certain that the queue is empty.
  503. //
  504. bool needAnotherThread = true;
  505. try
  506. {
  507. //
  508. // Set up our thread-local data
  509. //
  510. // Use operate on workQueue local to try block so it can be enregistered
  511. ThreadPoolWorkQueue workQueue = outerWorkQueue;
  512. ThreadPoolWorkQueueThreadLocals tl = workQueue.GetOrCreateThreadLocals();
  513. Thread currentThread = tl.currentThread;
  514. // Start on clean ExecutionContext and SynchronizationContext
  515. currentThread._executionContext = null;
  516. currentThread._synchronizationContext = null;
  517. //
  518. // Loop until our quantum expires or there is no work.
  519. //
  520. while (ThreadPool.KeepDispatching(startTickCount))
  521. {
  522. bool missedSteal = false;
  523. // Use operate on workItem local to try block so it can be enregistered
  524. object? workItem = workQueue.Dequeue(tl, ref missedSteal);
  525. if (workItem == null)
  526. {
  527. //
  528. // No work.
  529. // If we missed a steal, though, there may be more work in the queue.
  530. // Instead of looping around and trying again, we'll just request another thread. Hopefully the thread
  531. // that owns the contended work-stealing queue will pick up its own workitems in the meantime,
  532. // which will be more efficient than this thread doing it anyway.
  533. //
  534. needAnotherThread = missedSteal;
  535. // Tell the VM we're returning normally, not because Hill Climbing asked us to return.
  536. return true;
  537. }
  538. if (workQueue.loggingEnabled)
  539. System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolDequeueWorkObject(workItem);
  540. //
  541. // If we found work, there may be more work. Ask for another thread so that the other work can be processed
  542. // in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue.
  543. //
  544. workQueue.EnsureThreadRequested();
  545. //
  546. // Execute the workitem outside of any finally blocks, so that it can be aborted if needed.
  547. //
  548. if (ThreadPoolGlobals.enableWorkerTracking)
  549. {
  550. bool reportedStatus = false;
  551. try
  552. {
  553. ThreadPool.ReportThreadStatus(isWorking: true);
  554. reportedStatus = true;
  555. if (workItem is Task task)
  556. {
  557. task.ExecuteFromThreadPool(currentThread);
  558. }
  559. else
  560. {
  561. Debug.Assert(workItem is IThreadPoolWorkItem);
  562. Unsafe.As<IThreadPoolWorkItem>(workItem).Execute();
  563. }
  564. }
  565. finally
  566. {
  567. if (reportedStatus)
  568. ThreadPool.ReportThreadStatus(isWorking: false);
  569. }
  570. }
  571. else if (workItem is Task task)
  572. {
  573. // Check for Task first as it's currently faster to type check
  574. // for Task and then Unsafe.As for the interface, rather than
  575. // vice versa, in particular when the object implements a bunch
  576. // of interfaces.
  577. task.ExecuteFromThreadPool(currentThread);
  578. }
  579. else
  580. {
  581. Debug.Assert(workItem is IThreadPoolWorkItem);
  582. Unsafe.As<IThreadPoolWorkItem>(workItem).Execute();
  583. }
  584. currentThread.ResetThreadPoolThread();
  585. // Release refs
  586. workItem = null;
  587. // Return to clean ExecutionContext and SynchronizationContext
  588. ExecutionContext.ResetThreadPoolThread(currentThread);
  589. //
  590. // Notify the VM that we executed this workitem. This is also our opportunity to ask whether Hill Climbing wants
  591. // us to return the thread to the pool or not.
  592. //
  593. if (!ThreadPool.NotifyWorkItemComplete())
  594. return false;
  595. }
  596. // If we get here, it's because our quantum expired. Tell the VM we're returning normally.
  597. return true;
  598. }
  599. finally
  600. {
  601. //
  602. // If we are exiting for any reason other than that the queue is definitely empty, ask for another
  603. // thread to pick up where we left off.
  604. //
  605. if (needAnotherThread)
  606. outerWorkQueue.EnsureThreadRequested();
  607. }
  608. }
  609. }
  610. // Simple random number generator. We don't need great randomness, we just need a little and for it to be fast.
  611. internal struct FastRandom // xorshift prng
  612. {
  613. private uint _w, _x, _y, _z;
  614. public FastRandom(int seed)
  615. {
  616. _x = (uint)seed;
  617. _w = 88675123;
  618. _y = 362436069;
  619. _z = 521288629;
  620. }
  621. public int Next(int maxValue)
  622. {
  623. Debug.Assert(maxValue > 0);
  624. uint t = _x ^ (_x << 11);
  625. _x = _y; _y = _z; _z = _w;
  626. _w = _w ^ (_w >> 19) ^ (t ^ (t >> 8));
  627. return (int)(_w % (uint)maxValue);
  628. }
  629. }
  630. // Holds a WorkStealingQueue, and removes it from the list when this object is no longer referenced.
  631. internal sealed class ThreadPoolWorkQueueThreadLocals
  632. {
  633. [ThreadStatic]
  634. public static ThreadPoolWorkQueueThreadLocals? threadLocals;
  635. public readonly ThreadPoolWorkQueue workQueue;
  636. public readonly ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue;
  637. public readonly Thread currentThread;
  638. public FastRandom random = new FastRandom(Thread.CurrentThread.ManagedThreadId); // mutable struct, do not copy or make readonly
  639. public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq)
  640. {
  641. workQueue = tpq;
  642. workStealingQueue = new ThreadPoolWorkQueue.WorkStealingQueue();
  643. ThreadPoolWorkQueue.WorkStealingQueueList.Add(workStealingQueue);
  644. currentThread = Thread.CurrentThread;
  645. }
  646. ~ThreadPoolWorkQueueThreadLocals()
  647. {
  648. // Transfer any pending workitems into the global queue so that they will be executed by another thread
  649. if (null != workStealingQueue)
  650. {
  651. if (null != workQueue)
  652. {
  653. object? cb;
  654. while ((cb = workStealingQueue.LocalPop()) != null)
  655. {
  656. Debug.Assert(null != cb);
  657. workQueue.Enqueue(cb, forceGlobal: true);
  658. }
  659. }
  660. ThreadPoolWorkQueue.WorkStealingQueueList.Remove(workStealingQueue);
  661. }
  662. }
  663. }
  664. public delegate void WaitCallback(object? state);
  665. public delegate void WaitOrTimerCallback(object? state, bool timedOut); // signaled or timed out
  666. internal abstract class QueueUserWorkItemCallbackBase : IThreadPoolWorkItem
  667. {
  668. #if DEBUG
  669. private int executed;
  670. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1821:RemoveEmptyFinalizers")]
  671. ~QueueUserWorkItemCallbackBase()
  672. {
  673. Interlocked.MemoryBarrier(); // ensure that an old cached value is not read below
  674. Debug.Assert(
  675. executed != 0, "A QueueUserWorkItemCallback was never called!");
  676. }
  677. #endif
  678. public virtual void Execute()
  679. {
  680. #if DEBUG
  681. GC.SuppressFinalize(this);
  682. Debug.Assert(
  683. 0 == Interlocked.Exchange(ref executed, 1),
  684. "A QueueUserWorkItemCallback was called twice!");
  685. #endif
  686. }
  687. }
  688. internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallbackBase
  689. {
  690. private WaitCallback? _callback; // SOS's ThreadPool command depends on this name
  691. private readonly object? _state;
  692. private readonly ExecutionContext _context;
  693. private static readonly Action<QueueUserWorkItemCallback> s_executionContextShim = quwi =>
  694. {
  695. Debug.Assert(quwi._callback != null);
  696. WaitCallback callback = quwi._callback;
  697. quwi._callback = null;
  698. callback(quwi._state);
  699. };
  700. internal QueueUserWorkItemCallback(WaitCallback callback, object? state, ExecutionContext context)
  701. {
  702. Debug.Assert(context != null);
  703. _callback = callback;
  704. _state = state;
  705. _context = context;
  706. }
  707. public override void Execute()
  708. {
  709. base.Execute();
  710. ExecutionContext.RunForThreadPoolUnsafe(_context, s_executionContextShim, this);
  711. }
  712. }
  713. internal sealed class QueueUserWorkItemCallback<TState> : QueueUserWorkItemCallbackBase
  714. {
  715. private Action<TState>? _callback; // SOS's ThreadPool command depends on this name
  716. private readonly TState _state;
  717. private readonly ExecutionContext _context;
  718. internal QueueUserWorkItemCallback(Action<TState> callback, TState state, ExecutionContext context)
  719. {
  720. Debug.Assert(callback != null);
  721. _callback = callback;
  722. _state = state;
  723. _context = context;
  724. }
  725. public override void Execute()
  726. {
  727. base.Execute();
  728. Debug.Assert(_callback != null);
  729. Action<TState> callback = _callback;
  730. _callback = null;
  731. ExecutionContext.RunForThreadPoolUnsafe(_context, callback, in _state);
  732. }
  733. }
  734. internal sealed class QueueUserWorkItemCallbackDefaultContext : QueueUserWorkItemCallbackBase
  735. {
  736. private WaitCallback? _callback; // SOS's ThreadPool command depends on this name
  737. private readonly object? _state;
  738. internal QueueUserWorkItemCallbackDefaultContext(WaitCallback callback, object? state)
  739. {
  740. Debug.Assert(callback != null);
  741. _callback = callback;
  742. _state = state;
  743. }
  744. public override void Execute()
  745. {
  746. ExecutionContext.CheckThreadPoolAndContextsAreDefault();
  747. base.Execute();
  748. Debug.Assert(_callback != null);
  749. WaitCallback callback = _callback;
  750. _callback = null;
  751. callback(_state);
  752. // ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default
  753. }
  754. }
  755. internal sealed class QueueUserWorkItemCallbackDefaultContext<TState> : QueueUserWorkItemCallbackBase
  756. {
  757. private Action<TState>? _callback; // SOS's ThreadPool command depends on this name
  758. private readonly TState _state;
  759. internal QueueUserWorkItemCallbackDefaultContext(Action<TState> callback, TState state)
  760. {
  761. Debug.Assert(callback != null);
  762. _callback = callback;
  763. _state = state;
  764. }
  765. public override void Execute()
  766. {
  767. ExecutionContext.CheckThreadPoolAndContextsAreDefault();
  768. base.Execute();
  769. Debug.Assert(_callback != null);
  770. Action<TState> callback = _callback;
  771. _callback = null;
  772. callback(_state);
  773. // ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default
  774. }
  775. }
  776. internal sealed class _ThreadPoolWaitOrTimerCallback
  777. {
  778. private readonly WaitOrTimerCallback _waitOrTimerCallback;
  779. private readonly ExecutionContext? _executionContext;
  780. private readonly object? _state;
  781. private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
  782. private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
  783. internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object? state, bool flowExecutionContext)
  784. {
  785. _waitOrTimerCallback = waitOrTimerCallback;
  786. _state = state;
  787. if (flowExecutionContext)
  788. {
  789. // capture the exection context
  790. _executionContext = ExecutionContext.Capture();
  791. }
  792. }
  793. private static void WaitOrTimerCallback_Context_t(object? state) =>
  794. WaitOrTimerCallback_Context(state, timedOut: true);
  795. private static void WaitOrTimerCallback_Context_f(object? state) =>
  796. WaitOrTimerCallback_Context(state, timedOut: false);
  797. private static void WaitOrTimerCallback_Context(object? state, bool timedOut)
  798. {
  799. _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state!;
  800. helper._waitOrTimerCallback(helper._state, timedOut);
  801. }
  802. // call back helper
  803. internal static void PerformWaitOrTimerCallback(_ThreadPoolWaitOrTimerCallback helper, bool timedOut)
  804. {
  805. Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
  806. // call directly if it is an unsafe call OR EC flow is suppressed
  807. ExecutionContext? context = helper._executionContext;
  808. if (context == null)
  809. {
  810. WaitOrTimerCallback callback = helper._waitOrTimerCallback;
  811. callback(helper._state, timedOut);
  812. }
  813. else
  814. {
  815. ExecutionContext.Run(context, timedOut ? _ccbt : _ccbf, helper);
  816. }
  817. }
  818. }
  819. public static partial class ThreadPool
  820. {
  821. [CLSCompliant(false)]
  822. public static RegisteredWaitHandle RegisterWaitForSingleObject(
  823. WaitHandle waitObject,
  824. WaitOrTimerCallback callBack,
  825. object? state,
  826. uint millisecondsTimeOutInterval,
  827. bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
  828. )
  829. {
  830. if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue)
  831. throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
  832. return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, true);
  833. }
  834. [CLSCompliant(false)]
  835. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
  836. WaitHandle waitObject,
  837. WaitOrTimerCallback callBack,
  838. object? state,
  839. uint millisecondsTimeOutInterval,
  840. bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
  841. )
  842. {
  843. if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue)
  844. throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  845. return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, false);
  846. }
  847. public static RegisteredWaitHandle RegisterWaitForSingleObject(
  848. WaitHandle waitObject,
  849. WaitOrTimerCallback callBack,
  850. object? state,
  851. int millisecondsTimeOutInterval,
  852. bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
  853. )
  854. {
  855. if (millisecondsTimeOutInterval < -1)
  856. throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  857. return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true);
  858. }
  859. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
  860. WaitHandle waitObject,
  861. WaitOrTimerCallback callBack,
  862. object? state,
  863. int millisecondsTimeOutInterval,
  864. bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
  865. )
  866. {
  867. if (millisecondsTimeOutInterval < -1)
  868. throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  869. return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false);
  870. }
  871. public static RegisteredWaitHandle RegisterWaitForSingleObject(
  872. WaitHandle waitObject,
  873. WaitOrTimerCallback callBack,
  874. object? state,
  875. long millisecondsTimeOutInterval,
  876. bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
  877. )
  878. {
  879. if (millisecondsTimeOutInterval < -1)
  880. throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  881. if (millisecondsTimeOutInterval > (uint)int.MaxValue)
  882. throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
  883. return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true);
  884. }
  885. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
  886. WaitHandle waitObject,
  887. WaitOrTimerCallback callBack,
  888. object? state,
  889. long millisecondsTimeOutInterval,
  890. bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
  891. )
  892. {
  893. if (millisecondsTimeOutInterval < -1)
  894. throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  895. if (millisecondsTimeOutInterval > (uint)int.MaxValue)
  896. throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
  897. return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false);
  898. }
  899. public static RegisteredWaitHandle RegisterWaitForSingleObject(
  900. WaitHandle waitObject,
  901. WaitOrTimerCallback callBack,
  902. object? state,
  903. TimeSpan timeout,
  904. bool executeOnlyOnce
  905. )
  906. {
  907. long tm = (long)timeout.TotalMilliseconds;
  908. if (tm < -1)
  909. throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  910. if (tm > (long)int.MaxValue)
  911. throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
  912. return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, true);
  913. }
  914. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
  915. WaitHandle waitObject,
  916. WaitOrTimerCallback callBack,
  917. object? state,
  918. TimeSpan timeout,
  919. bool executeOnlyOnce
  920. )
  921. {
  922. long tm = (long)timeout.TotalMilliseconds;
  923. if (tm < -1)
  924. throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
  925. if (tm > (long)int.MaxValue)
  926. throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
  927. return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, false);
  928. }
  929. public static bool QueueUserWorkItem(WaitCallback callBack) =>
  930. QueueUserWorkItem(callBack, null);
  931. public static bool QueueUserWorkItem(WaitCallback callBack, object? state)
  932. {
  933. if (callBack == null)
  934. {
  935. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
  936. }
  937. EnsureInitialized();
  938. ExecutionContext? context = ExecutionContext.Capture();
  939. object tpcallBack = (context == null || context.IsDefault) ?
  940. new QueueUserWorkItemCallbackDefaultContext(callBack!, state) :
  941. (object)new QueueUserWorkItemCallback(callBack!, state, context);
  942. ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
  943. return true;
  944. }
  945. public static bool QueueUserWorkItem<TState>(Action<TState> callBack, TState state, bool preferLocal)
  946. {
  947. if (callBack == null)
  948. {
  949. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
  950. }
  951. EnsureInitialized();
  952. ExecutionContext? context = ExecutionContext.Capture();
  953. object tpcallBack = (context == null || context.IsDefault) ?
  954. new QueueUserWorkItemCallbackDefaultContext<TState>(callBack!, state) :
  955. (object)new QueueUserWorkItemCallback<TState>(callBack!, state, context);
  956. ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: !preferLocal);
  957. return true;
  958. }
  959. public static bool UnsafeQueueUserWorkItem<TState>(Action<TState> callBack, TState state, bool preferLocal)
  960. {
  961. if (callBack == null)
  962. {
  963. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
  964. }
  965. // If the callback is the runtime-provided invocation of an IAsyncStateMachineBox,
  966. // then we can queue the Task state directly to the ThreadPool instead of
  967. // wrapping it in a QueueUserWorkItemCallback.
  968. //
  969. // This occurs when user code queues its provided continuation to the ThreadPool;
  970. // internally we call UnsafeQueueUserWorkItemInternal directly for Tasks.
  971. if (ReferenceEquals(callBack, ThreadPoolGlobals.s_invokeAsyncStateMachineBox))
  972. {
  973. if (!(state is IAsyncStateMachineBox))
  974. {
  975. // The provided state must be the internal IAsyncStateMachineBox (Task) type
  976. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state);
  977. }
  978. UnsafeQueueUserWorkItemInternal((object)state!, preferLocal);
  979. return true;
  980. }
  981. EnsureInitialized();
  982. ThreadPoolGlobals.workQueue.Enqueue(
  983. new QueueUserWorkItemCallbackDefaultContext<TState>(callBack!, state), forceGlobal: !preferLocal);
  984. return true;
  985. }
  986. public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object? state)
  987. {
  988. if (callBack == null)
  989. {
  990. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
  991. }
  992. EnsureInitialized();
  993. object tpcallBack = new QueueUserWorkItemCallbackDefaultContext(callBack!, state);
  994. ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
  995. return true;
  996. }
  997. public static bool UnsafeQueueUserWorkItem(IThreadPoolWorkItem callBack, bool preferLocal)
  998. {
  999. if (callBack == null)
  1000. {
  1001. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack);
  1002. }
  1003. if (callBack is Task)
  1004. {
  1005. // Prevent code from queueing a derived Task that also implements the interface,
  1006. // as that would bypass Task.Start and its safety checks.
  1007. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.callBack);
  1008. }
  1009. UnsafeQueueUserWorkItemInternal(callBack!, preferLocal);
  1010. return true;
  1011. }
  1012. internal static void UnsafeQueueUserWorkItemInternal(object callBack, bool preferLocal)
  1013. {
  1014. Debug.Assert((callBack is IThreadPoolWorkItem) ^ (callBack is Task));
  1015. EnsureInitialized();
  1016. ThreadPoolGlobals.workQueue.Enqueue(callBack, forceGlobal: !preferLocal);
  1017. }
  1018. // This method tries to take the target callback out of the current thread's queue.
  1019. internal static bool TryPopCustomWorkItem(object workItem)
  1020. {
  1021. Debug.Assert(null != workItem);
  1022. return
  1023. ThreadPoolGlobals.threadPoolInitialized && // if not initialized, so there's no way this workitem was ever queued.
  1024. ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem);
  1025. }
  1026. // Get all workitems. Called by TaskScheduler in its debugger hooks.
  1027. internal static IEnumerable<object> GetQueuedWorkItems()
  1028. {
  1029. // Enumerate global queue
  1030. foreach (object workItem in ThreadPoolGlobals.workQueue.workItems)
  1031. {
  1032. yield return workItem;
  1033. }
  1034. // Enumerate each local queue
  1035. foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.WorkStealingQueueList.Queues)
  1036. {
  1037. if (wsq != null && wsq.m_array != null)
  1038. {
  1039. object?[] items = wsq.m_array;
  1040. for (int i = 0; i < items.Length; i++)
  1041. {
  1042. object? item = items[i];
  1043. if (item != null)
  1044. {
  1045. yield return item;
  1046. }
  1047. }
  1048. }
  1049. }
  1050. }
  1051. internal static IEnumerable<object> GetLocallyQueuedWorkItems()
  1052. {
  1053. ThreadPoolWorkQueue.WorkStealingQueue? wsq = ThreadPoolWorkQueueThreadLocals.threadLocals?.workStealingQueue;
  1054. if (wsq != null && wsq.m_array != null)
  1055. {
  1056. object?[] items = wsq.m_array;
  1057. for (int i = 0; i < items.Length; i++)
  1058. {
  1059. object? item = items[i];
  1060. if (item != null)
  1061. yield return item;
  1062. }
  1063. }
  1064. }
  1065. internal static IEnumerable<object> GetGloballyQueuedWorkItems() => ThreadPoolGlobals.workQueue.workItems;
  1066. private static object[] ToObjectArray(IEnumerable<object> workitems)
  1067. {
  1068. int i = 0;
  1069. foreach (object item in workitems)
  1070. {
  1071. i++;
  1072. }
  1073. object[] result = new object[i];
  1074. i = 0;
  1075. foreach (object item in workitems)
  1076. {
  1077. if (i < result.Length) // just in case someone calls us while the queues are in motion
  1078. result[i] = item;
  1079. i++;
  1080. }
  1081. return result;
  1082. }
  1083. // This is the method the debugger will actually call, if it ends up calling
  1084. // into ThreadPool directly. Tests can use this to simulate a debugger, as well.
  1085. internal static object[] GetQueuedWorkItemsForDebugger() =>
  1086. ToObjectArray(GetQueuedWorkItems());
  1087. internal static object[] GetGloballyQueuedWorkItemsForDebugger() =>
  1088. ToObjectArray(GetGloballyQueuedWorkItems());
  1089. internal static object[] GetLocallyQueuedWorkItemsForDebugger() =>
  1090. ToObjectArray(GetLocallyQueuedWorkItems());
  1091. /// <summary>
  1092. /// Gets the number of work items that are currently queued to be processed.
  1093. /// </summary>
  1094. /// <remarks>
  1095. /// For a thread pool implementation that may have different types of work items, the count includes all types that can
  1096. /// be tracked, which may only be the user work items including tasks. Some implementations may also include queued
  1097. /// timer and wait callbacks in the count. On Windows, the count is unlikely to include the number of pending IO
  1098. /// completions, as they get posted directly to an IO completion port.
  1099. /// </remarks>
  1100. public static long PendingWorkItemCount
  1101. {
  1102. get
  1103. {
  1104. ThreadPoolWorkQueue workQueue = ThreadPoolGlobals.workQueue;
  1105. return workQueue.LocalCount + workQueue.GlobalCount + PendingUnmanagedWorkItemCount;
  1106. }
  1107. }
  1108. }
  1109. }