ThreadPool.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 increases the number of threads if needed
  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.IsThreadPoolThreadInternal = true;
  76. Start.Start();
  77. _Threads.Add(Start);
  78. }
  79. }
  80. internal void AddItem(ref ThreadPoolWorkItem Item) {
  81. if (Interlocked.Increment(ref _RequestInQueue) == 1) {
  82. _DataInQueue.Set();
  83. }
  84. _RequestQueue.Enqueue(Item);
  85. }
  86. // Work Thread main function
  87. internal void WorkerThread() {
  88. bool bWaitForData = true;
  89. while (true) {
  90. if (bWaitForData) {
  91. if (!_DataInQueue.WaitOne(_ThreadTimeout, false)) {
  92. // timeout
  93. RemoveThread();
  94. return;
  95. }
  96. }
  97. Interlocked.Increment(ref _ThreadsInUse);
  98. try {
  99. ThreadPoolWorkItem oItem = (ThreadPoolWorkItem) _RequestQueue.Dequeue();
  100. if (Interlocked.Decrement(ref _RequestInQueue) == 0) {
  101. _DataInQueue.Reset();
  102. }
  103. oItem._CallBack(oItem._Context);
  104. }
  105. catch (InvalidOperationException) {
  106. // Queue empty
  107. bWaitForData = true;
  108. }
  109. catch (ThreadAbortException) {
  110. // We will leave here.. (thread abort can't be handled)
  111. RemoveThread();
  112. }
  113. finally {
  114. Interlocked.Decrement(ref _ThreadsInUse);
  115. }
  116. }
  117. }
  118. internal void MonitorThread() {
  119. while (true) {
  120. if (_DataInQueue.WaitOne ()) {
  121. CheckIfStartThread();
  122. }
  123. Thread.Sleep(500);
  124. }
  125. }
  126. internal bool QueueUserWorkItemInternal(WaitCallback callback) {
  127. return QueueUserWorkItem(callback, null);
  128. }
  129. internal bool QueueUserWorkItemInternal(WaitCallback callback, object context) {
  130. ThreadPoolWorkItem Item = new ThreadPoolWorkItem();
  131. Item._CallBack = callback;
  132. Item._Context = context;
  133. AddItem(ref Item);
  134. // LAMESPEC: Return value? should use exception here if anything goes wrong
  135. return true;
  136. }
  137. public static bool BindHandle(IntPtr osHandle) {
  138. throw new NotSupportedException("This is a win32 specific method, not supported Mono");
  139. }
  140. public static bool QueueUserWorkItem(WaitCallback callback) {
  141. return _Threadpool.QueueUserWorkItemInternal(callback);
  142. }
  143. public static bool QueueUserWorkItem(WaitCallback callback, object state) {
  144. return _Threadpool.QueueUserWorkItemInternal(callback, state);
  145. }
  146. public static bool UnsafeQueueUserWorkItem(WaitCallback callback, object state) {
  147. return _Threadpool.QueueUserWorkItemInternal(callback, state);
  148. }
  149. [MonoTODO]
  150. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) {
  151. if (millisecondsTimeOutInterval < -1) {
  152. throw new ArgumentOutOfRangeException("timeout < -1");
  153. }
  154. throw new NotImplementedException();
  155. }
  156. [MonoTODO]
  157. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) {
  158. if (millisecondsTimeOutInterval < -1) {
  159. throw new ArgumentOutOfRangeException("timeout < -1");
  160. }
  161. throw new NotImplementedException();
  162. }
  163. [MonoTODO]
  164. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce) {
  165. // LAMESPEC: I assume it means "timeout" when it says "millisecondsTimeOutInterval"
  166. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  167. if (ms < -1) {
  168. throw new ArgumentOutOfRangeException("timeout < -1");
  169. }
  170. if (ms > Int32.MaxValue) {
  171. throw new NotSupportedException("timeout too large");
  172. }
  173. throw new NotImplementedException();
  174. }
  175. [CLSCompliant(false)][MonoTODO]
  176. public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) {
  177. throw new NotImplementedException();
  178. }
  179. [MonoTODO]
  180. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) {
  181. throw new NotImplementedException();
  182. }
  183. [MonoTODO]
  184. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) {
  185. throw new NotImplementedException();
  186. }
  187. [MonoTODO]
  188. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce) {
  189. throw new NotImplementedException();
  190. }
  191. [CLSCompliant(false)][MonoTODO]
  192. public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callback, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) {
  193. throw new NotImplementedException();
  194. }
  195. }
  196. }