ThreadPool.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //
  2. // System.Threading.ThreadPool
  3. //
  4. // Author:
  5. // Patrik Torstensson ([email protected])
  6. // Dick Porter ([email protected])
  7. //
  8. // (C) Ximian, Inc. http://www.ximian.com
  9. // (C) Patrik Torstensson
  10. //
  11. using System;
  12. using System.Collections;
  13. namespace System.Threading
  14. {
  15. /// <summary> (Patrik T notes)
  16. /// This threadpool is focused on saving resources not giving max performance.
  17. ///
  18. /// Note, this class is not perfect but it works. ;-) Should also replace
  19. /// the queue with an internal one (performance)
  20. ///
  21. /// This class should also use a specialized queue to increase performance..
  22. /// </summary
  23. ///
  24. public sealed class ThreadPool {
  25. internal struct ThreadPoolWorkItem {
  26. public WaitCallback _CallBack;
  27. public object _Context;
  28. }
  29. private int _ThreadTimeout;
  30. private long _MaxThreads;
  31. private long _CurrentThreads;
  32. private long _ThreadsInUse;
  33. private long _RequestInQueue;
  34. private long _ThreadCreateTriggerRequests;
  35. private Thread _MonitorThread;
  36. private Queue _RequestQueue;
  37. private ArrayList _Threads;
  38. private ManualResetEvent _DataInQueue;
  39. static ThreadPool _Threadpool;
  40. static ThreadPool() {
  41. _Threadpool = new ThreadPool();
  42. }
  43. private ThreadPool() {
  44. // 30 sec timeout default
  45. _ThreadTimeout = 30 * 1000;
  46. // Used to signal that there is data in the queue
  47. _DataInQueue = new ManualResetEvent(false);
  48. _Threads = ArrayList.Synchronized(new ArrayList());
  49. // Holds requests..
  50. _RequestQueue = Queue.Synchronized(new Queue(128));
  51. _MaxThreads = 64;
  52. _CurrentThreads = 0;
  53. _RequestInQueue = 0;
  54. _ThreadsInUse = 0;
  55. _ThreadCreateTriggerRequests = 5;
  56. // Keeps track of requests in the queue and inreases the number of threads if neededs
  57. _MonitorThread = new Thread(new ThreadStart(MonitorThread));
  58. _MonitorThread.Start();
  59. }
  60. internal void RemoveThread() {
  61. Interlocked.Decrement(ref _CurrentThreads);
  62. _Threads.Remove(Thread.CurrentThread);
  63. }
  64. internal void CheckIfStartThread() {
  65. bool bCreateThread = false;
  66. if (_CurrentThreads == 0) {
  67. bCreateThread = true;
  68. }
  69. if ((_MaxThreads == -1 || _CurrentThreads < _MaxThreads) && _ThreadsInUse > 0 && _RequestInQueue > _ThreadCreateTriggerRequests) {
  70. bCreateThread = true;
  71. }
  72. if (bCreateThread) {
  73. Interlocked.Increment(ref _CurrentThreads);
  74. Thread Start = new Thread(new ThreadStart(WorkerThread));
  75. Start.Start();
  76. Start.IsThreadPoolThreadInternal = true;
  77. _Threads.Add(Start);
  78. }
  79. }
  80. internal void AddItem(ref ThreadPoolWorkItem Item) {
  81. CheckIfStartThread();
  82. if (Interlocked.Increment(ref _RequestInQueue) == 1) {
  83. _DataInQueue.Set();
  84. }
  85. _RequestQueue.Enqueue(Item);
  86. }
  87. // Work Thread main function
  88. internal void WorkerThread() {
  89. bool bWaitForData = true;
  90. while (true) {
  91. if (bWaitForData) {
  92. if (!_DataInQueue.WaitOne(_ThreadTimeout, false)) {
  93. // timeout
  94. RemoveThread();
  95. return;
  96. }
  97. }
  98. Interlocked.Increment(ref _ThreadsInUse);
  99. try {
  100. ThreadPoolWorkItem oItem = (ThreadPoolWorkItem) _RequestQueue.Dequeue();
  101. if (Interlocked.Decrement(ref _RequestInQueue) == 0) {
  102. _DataInQueue.Reset();
  103. }
  104. oItem._CallBack(oItem._Context);
  105. }
  106. catch (InvalidOperationException) {
  107. // Queue empty
  108. bWaitForData = true;
  109. }
  110. catch (ThreadAbortException) {
  111. // We will leave here.. (thread abort can't be handled)
  112. RemoveThread();
  113. }
  114. finally {
  115. Interlocked.Decrement(ref _ThreadsInUse);
  116. }
  117. }
  118. }
  119. internal void MonitorThread() {
  120. while (true) {
  121. Thread.Sleep(500);
  122. CheckIfStartThread();
  123. }
  124. }
  125. internal bool QueueUserWorkItemInternal(WaitCallback callback) {
  126. return QueueUserWorkItem(callback, null);
  127. }
  128. internal bool QueueUserWorkItemInternal(WaitCallback callback, object context) {
  129. ThreadPoolWorkItem Item = new ThreadPoolWorkItem();
  130. Item._CallBack = callback;
  131. Item._Context = context;
  132. AddItem(ref Item);
  133. // LAMESPEC: Return value? should use exception here if anything goes wrong
  134. return true;
  135. }
  136. public static bool BindHandle(IntPtr osHandle) {
  137. throw new NotSupportedException("This is a win32 specific method, not supported Mono");
  138. }
  139. public static bool QueueUserWorkItem(WaitCallback callback) {
  140. return _Threadpool.QueueUserWorkItemInternal(callback);
  141. }
  142. public static bool QueueUserWorkItem(WaitCallback callback, object state) {
  143. return _Threadpool.QueueUserWorkItemInternal(callback, state);
  144. }
  145. public static bool UnsafeQueueUserWorkItem(WaitCallback callback, object state) {
  146. return _Threadpool.QueueUserWorkItemInternal(callback, state);
  147. }
  148. [MonoTODO]
  149. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) {
  150. if (millisecondsTimeOutInterval < -1) {
  151. throw new ArgumentOutOfRangeException("timeout < -1");
  152. }
  153. throw new NotImplementedException();
  154. }
  155. [MonoTODO]
  156. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) {
  157. if (millisecondsTimeOutInterval < -1) {
  158. throw new ArgumentOutOfRangeException("timeout < -1");
  159. }
  160. throw new NotImplementedException();
  161. }
  162. [MonoTODO]
  163. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce) {
  164. // LAMESPEC: I assume it means "timeout" when it says "millisecondsTimeOutInterval"
  165. if (timeout.Milliseconds < -1) {
  166. throw new ArgumentOutOfRangeException("timeout < -1");
  167. }
  168. if (timeout.Milliseconds > Int32.MaxValue) {
  169. throw new NotSupportedException("timeout too large");
  170. }
  171. throw new NotImplementedException();
  172. }
  173. [CLSCompliant(false)][MonoTODO]
  174. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) {
  175. throw new NotImplementedException();
  176. }
  177. [MonoTODO]
  178. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) {
  179. throw new NotImplementedException();
  180. }
  181. [MonoTODO]
  182. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) {
  183. throw new NotImplementedException();
  184. }
  185. [MonoTODO]
  186. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce) {
  187. throw new NotImplementedException();
  188. }
  189. [CLSCompliant(false)][MonoTODO]
  190. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) {
  191. throw new NotImplementedException();
  192. }
  193. }
  194. }